在不清除缓冲区的情况下查看httppostedbase内存流

时间:2014-01-26 09:43:09

标签: c# asp.net-mvc httppostedfilebase

我想查看HttpPostedBaseFile中的字节来查看上传的内容。当我打开流时,它似乎清除了数据

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

...
}

我想保留HttpPostedFileBase的InputStream,或者给出它已被保留的外观。如何在保留InputStream的同时读取/查看多个字节?


编辑: 我采用了另一种方法并读取流数据,并将元数据流式传输到poco中。然后我绕过了POCO,例如

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; }
}

1 个答案:

答案 0 :(得分:2)

你不能寻求NetworkStream。一旦你阅读它,它就消失了。

如果必须这样做,请创建MemoryStream并使用Stream.CopyTo将内容复制到其中。然后,你可以用内存流做任何你喜欢的事情。

相关问题