Search code examples
c#filestream

How to write .csv from request stream


I am trying to upload a .csv files from my website to my server .

The files are copied to the server just fine and are the same size as the originally uploaded .csv files.

The problem is when I open the .csv files on the server the content of the file is empty.

Here is my uploader method:

public bool UploadCsvFile(Stream uploadFileStream, string fileExtension)
        {
            byte[] fileData = new byte[(int)uploadFileStream.Length];
            string hashname = BitConverter.ToString(MD5CryptoServiceProvider.Create().ComputeHash(fileData)).Replace("-", string.Empty);
            DateTime now = DateTime.Now;
            string originalImageName = hashname + now.Year + now.Day + now.Month + now.Hour + now.Minute + now.Second + now.Millisecond + fileExtension;
            var dropFolder = ConfigurationManager.AppSettings["mydrop"];

            var fileNamePath = Path.Combine(dropFolder, originalImageName);

            try
             {
              try
               {
                   var fileStream = File.Create(fileNamePath);
                   fileStream.Write(fileData, 0, fileData.Length);
                  fileStream.Close();

            //I also tried this:
                  //var fileStream = File.Create(fileNamePath, (int)uploadFileStream.Length);
                 // fileStream.Read(fileData, 0, fileData.Length);
                  //fileStream.Write(fileData, 0, fileData.Length);
                 // fileStream.Close();


                }
                catch (Exception exc)
                {
                    throw exc;
                }
              }
                catch (Exception ex)
                {
                    throw ex;
                }

            return true;
        }

Solution

  • You should be able to get that done as simply as:

    var fileStream = File.Create(fileNamePath);
    
    uploadFileStream.copyTo(fileStream);