正在上传docx损坏的文件

时间:2010-12-22 00:06:09

标签: c# asp.net

我正在使用以下代码上传文件。文件上传没有错误,但是当我打开一个扩展名为.docx的文件时,M $表示该文件已损坏。然而,它能够修复文件然后打开。我想解决这个问题,以便正确打开文档。

string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
string fileName = @"C:\" + Guid.NewGuid().ToString() + strExtension;
using (FileStream fs = new FileStream(fileName, FileMode.CreateNew))
{
    byte[] bytes = new byte[16 * 1024];

    int bytesRead;
    while ((bytesRead = context.Request.InputStream.Read(bytes, 0, bytes.Length)) > 0)
    {
        fs.Write(bytes, 0, bytesRead);
    }
} 

感谢。

编辑:

使用以下代码正确保存文件:

while ((bytesRead = context.Request.Files[0].InputStream.Read(bytes, 0, bytes.Length)) > 0)

还可以使用context.Request.Files[0].SaveAs(...);

正确保存

2 个答案:

答案 0 :(得分:3)

看起来你正在阅读HttpRequest.InputStream。最好的办法是检查HttpRequest.Files集合。

(或者更简单,使用FileUpload服务器控件)。

您的代码正在将原始输入(很可能是多部分)复制到文件中。

答案 1 :(得分:1)

这不能完全回答您的问题,但您可以使用HttpPostedFile.SaveAs将内容保存到所需的路径。

string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
string fileName = @"C:\" + Guid.NewGuid().ToString() + strExtension;
context.Request.Files[0].SaveAs(fileName); // i'll ignore the violation of the law of demeter ;)
相关问题