0

I am attempting to save an Excel (.xlsx) file in disk that is sent to a webservice. The code I have used is as follows, However when I click on the saved file it returns a "The File is corrupt and cannot be opened" error. But the same methodology works for CSV files.

  string dataFile = await Request.Content.ReadAsStringAsync();
  byte[] byteArray = Encoding.UTF8.GetBytes(dataFile);
  MemoryStream stream_ = new MemoryStream(byteArray);
  MultipartParser.MultipartParser mp = new MultipartParser.MultipartParser(stream_);

  // Save Excel file
  File.WriteAllBytes(@"C:\temp\output.xlsx", mp.FileContents);
DafaDil
  • 2,463
  • 6
  • 23
  • 33

1 Answers1

2

The following worked,

        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);

        try
        {
            string fileName = "";
            string fileLocalName = "";
            var result = await Request.Content.ReadAsMultipartAsync(provider);
            foreach (MultipartFileData file in provider.FileData)
            {
                fileLocalName = file.LocalFileName;
            }

            File.WriteAllBytes(@"C:\temp\output.xlsx", File.ReadAllBytes(fileLocalName));
        }

Thanks for the help, Ben Robinson, Daniel A. White, Ali Sepehri.Kh and Faisal Hafeez for the help

DafaDil
  • 2,463
  • 6
  • 23
  • 33