Skip to main content
 首页 » 编程设计

c#之上传 docx 损坏文件

2024年02月23日14powertoolsteam

我正在使用下面的代码上传文件。文件上传没有错误,但是当我打开一个扩展名为 .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(...); 正确保存

请您参考如下方法:

看起来您正在阅读 HttpRequest.InputStream .更好的做法是检查 HttpRequest.Files收藏。

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

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