Question

I want to look at the bytes in a HttpPostedBaseFile to look at the content uploaded. when I open the stream though, it appears to clear the data

private bool IsAWordDocument(HttpPostedFileBase httpPostedFileBase)
{

   ....
   byte[] contents = null;
   using (var binaryReader = new BinaryReader(httpPostedFileBase.InputStream))
   {
       contents = binaryReader.ReadBytes(10);
       //binaryReader.BaseStream.Position = 0;
   }

   //InputStream is empty when I get to here!
  var properBytes = contents.Take(8).SequenceEqual(DOC) || contents.Take(4).SequenceEqual(ZIP_DOCX);
  httpPostedFileBase.InputStream.Position = 0; //reset stream position

...
}

I want to preserve the HttpPostedFileBase's InputStream, or give the appearance that it has been preserved. How do I read / peek at many bytes while still preserving the InputStream?


Edit: I took an alternate approach and read the stream data, and stream meta data into a poco. Then I passed the POCO around, eg.

public class FileData
{
    public FileData(HttpPostedFileBase file)
    {
        ContentLength = file.ContentLength;
        ContentType = file.ContentType;
        FileExtension = Path.GetExtension(file.FileName);
        FileName = Path.GetFileName(file.FileName);

        using (var binaryReader = new BinaryReader(file.InputStream))
        {
            Contents = binaryReader.ReadBytes(file.ContentLength);
        }

    }
    public string FileName { get; set; }
    public string FileExtension { get; set; }
    public string ContentType { get; set; }
    public int ContentLength { get; set; }
    public byte[] Contents { get; set; }
}
Was it helpful?

Solution

You cannot seek a NetworkStream. Once you read it, it is gone.

If you have to do this, create a MemoryStream and use Stream.CopyTo to copy the contents into that. Then, you can do anything you like with the memory stream.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top