OpenXml Cannot open package because FileMode or FileAccess value is not valid for the stream

hidden picture hidden · Jul 26, 2013 · Viewed 7.5k times · Source

The stream comes from an html form via ajax var jqXHR = data.submit();

public static GetWordPlainText(Stream readStream,string filePath)
{
   WordprocessingDocument.Open(readStream, readStream.CanRead);
}
[HttpPost]
public ActionResult FileUpload() 
{
 var MyFile = Request.Files[0];
 if (Request.Files.Count > 0 && MyFile != null)
 {
  GetWordPlainText(Request.InputStream);
 }
}

I get this error:

Cannot open package because FileMode or FileAccess value is not valid for the stream.

I google Cannot open package because FileMode or FileAccess value is not valid for the stream but can't find anything useful. Any ideas?

PS: Initially I simplified the code to be posted here to much. Added the if statement so that it would erase the concern by Sten Petrov. I hope Request.File.count>0 does address his concern... I still have the same problem...

UPDATE

As a work around I followed the advise below and save the file to a directory then I use openxml to read it from the directory

  var MyFile = Request.Files[0];
  var path = Path.Combine(Server.MapPath("~/App_Data/temp"), MyFile.FileName);
                using (MemoryStream ms = new MemoryStream())
                {
                    //if file exist plz!!!! TODO

                    Request.Files[0].InputStream.CopyTo(ms);
                    System.IO.File.WriteAllBytes(path, ms.ToArray());
                }

then WordprocessingDocument.Open has a implementation for filepath so WordprocessingDocument.Open(path); hope you get the idea of what I did for future people that have problems.

Answer

Sten Petrov picture Sten Petrov · Jul 26, 2013

What you're doing is asking for trouble, because the Request stream may not have fully been downloaded.

I suggest you download the file first into a MemoryStream or as a file, see here for the latter option, then do whatever you want to the uploaded file.