1

我想查看 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; }
}
4

1 回答 1

2

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

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

于 2014-01-26T10:58:19.933 回答