C# 如何从HttpPostedFile InputStream属性读取正确的流/字节[]?
我得到一个正在上传的C# 如何从HttpPostedFile InputStream属性读取正确的流/字节[]?,c#,http,memory,io,stream,C#,Http,Memory,Io,Stream,我得到一个正在上传的HttpPostedFile(应该是pdf),我必须使用它的流在PdfSharp中初始化它 问题是,尽管HttpPostedFileSaveAs()方法保存了一个有效的pdf,但保存它的InputStream并不会创建一个有效的pdf,所以当我在PdfSharp上使用InputStream读取pdf时,它会抛出一个异常,其中包含“无效的pdf”,并保存InputStream字节[] 我试着这样做: public byte[] GetBytesFromStream(Sy
HttpPostedFile
(应该是pdf),我必须使用它的流
在PdfSharp中初始化它
问题是,尽管HttpPostedFile
SaveAs()
方法保存了一个有效的pdf,但保存它的InputStream
并不会创建一个有效的pdf,所以当我在PdfSharp上使用InputStream
读取pdf时,它会抛出一个异常,其中包含“无效的pdf”,并保存InputStream
字节[]
我试着这样做:
public byte[] GetBytesFromStream(System.IO.Stream uploadedFile)
{
int length = Convert.ToInt32(uploadedFile.Length); //Length: 103050706
string str = "";
byte[] input = new byte[length];
// Initialize the stream.
System.IO.Stream MyStream = uploadedFile;
// Read the file into the byte array.
MyStream.Read(input, 0, length);
return input;
}
byte[] fileBytes = GetBytesFromStream(uploadedFile.InputStream);
按如下方式调用该方法:
public byte[] GetBytesFromStream(System.IO.Stream uploadedFile)
{
int length = Convert.ToInt32(uploadedFile.Length); //Length: 103050706
string str = "";
byte[] input = new byte[length];
// Initialize the stream.
System.IO.Stream MyStream = uploadedFile;
// Read the file into the byte array.
MyStream.Read(input, 0, length);
return input;
}
byte[] fileBytes = GetBytesFromStream(uploadedFile.InputStream);
但是从这些字节创建文件也会创建无效的pdf
我用这样的字节创建了这个文件
System.IO.File.WriteAllBytes("Foo.pdf", fileBytes);
关于这一点,我有两个问题:
1-为什么我从InputStream接收的流无效,而SaveAs工作
第二-如何从inputStream或HttpPostedFile中获得正确的流,而不将文件保存到磁盘然后读取它。检查inputStream位置,它可能不是0,所以在读取字节数组之前将其设置为0。我不知道该说什么,但谢谢!我怎么没想到!非常感谢你!