Monday, February 9, 2015

Upload a file in ASP.NET

http://www.codeproject.com/Articles/1757/File-Upload-with-ASP-NET

public string UploadPersonalFile(HttpPostedFile myFile, string ContactID)
        {
          
            proposalcenterfunctions proposalfunctions = new proposalcenterfunctions();
this.strRootFilePath = @"" + ConfigurationManager.AppSettings["CensusDataFilesParentDirectory"];

            ProjectPath = "Contacts\\" + ContactID;
            PhysicalDirPath = strRootFilePath + ProjectPath;
            DirectoryInfo clientDir = new DirectoryInfo(PhysicalDirPath);
            if (clientDir.Exists == false)
            {
                clientDir.Create();
            }
            // Get size of uploaded file
            int nFileLen = myFile.ContentLength;
            try
            {
                // make sure the size of the file is > 0
                if (nFileLen > 0)
                {
                    // Allocate a buffer for reading of the file
                    byte[] myData = new byte[nFileLen];
                    // Read uploaded file from the Stream
                    myFile.InputStream.Read(myData, 0, nFileLen);
                    // Create a name for the file to store
                    string strFilename = Path.GetFileName(myFile.FileName);
                    string Extension = strFilename.Remove(0, strFilename.LastIndexOf('.'));
                    string fileName = strFilename.Substring(0, strFilename.Length - Extension.Length);
                    var dateTime = DateTime.Now.ToString("MMddyy_hh-mm-ss");
                    strFilename = fileName + "_" + dateTime + Extension;
                    strFullFilePath = PhysicalDirPath + "\\" + strFilename;
                    proposalfunctions.WriteToFile(strFullFilePath, ref myData);
                }
                else
                {
                    strFullFilePath = "";
                }
            }
            catch (Exception ex)
            {
                ExceptionLogger.WriteLog(ex, "UploadFile");
            }

            return strFullFilePath;
        }



 public void WriteToFile(string strPath, ref byte[] Buffer)
        {
            FileStream stream = new FileStream(strPath, FileMode.Create);
            stream.Write(Buffer, 0, Buffer.Length);
            stream.Close();
        }

No comments:

Post a Comment