C# 检查docx是否已损坏
我尝试了许多解决方案,但代码总是检查损坏的文件并发送trueC# 检查docx是否已损坏,c#,file,openxml,C#,File,Openxml,我尝试了许多解决方案,但代码总是检查损坏的文件并发送true using (FileStream fileStream = File.OpenRead(path[0])) { MemoryStream memStream = new MemoryStream(); memStream.SetLength(fileStream.Length); fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length)
using (FileStream fileStream = File.OpenRead(path[0]))
{
MemoryStream memStream = new MemoryStream();
memStream.SetLength(fileStream.Length);
fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");
HttpContext.Current.Response.BinaryWrite(memStream.ToArray());
HttpContext.Current.Response.Flush();
// HttpContext.Current.Response.Close();
HttpContext.Current.Response.End();
}
其中路径[0]是我的docx位置..它仍然读取损坏的文件并且不会引发任何错误..任何建议请..您可以从中使用OpenXmlValidator来验证MS Office文档,如下所示
OpenXmlValidator validator = new OpenXmlValidator();
bool isValid=validator.Validate(WordprocessingDocument.Open("InvalidFile.docx", true)).Count()==0
请查看此页面:
使用,您可以编写如下代码:
public static void ValidateWordDocument(string filepath)
{
using (var wordprocessingDocument = WordprocessingDocument.Open(filepath, true))
{
try
{
OpenXmlValidator validator = new OpenXmlValidator();
int count = 0;
foreach (ValidationErrorInfo error in
validator.Validate(wordprocessingDocument))
{
count++;
Console.WriteLine("Error " + count);
Console.WriteLine("Description: " + error.Description);
Console.WriteLine("ErrorType: " + error.ErrorType);
Console.WriteLine("Node: " + error.Node);
Console.WriteLine("Path: " + error.Path.XPath);
Console.WriteLine("Part: " + error.Part.Uri);
Console.WriteLine("-------------------------------------------");
}
Console.WriteLine("count={0}", count);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
wordprocessingDocument.Close();
}
}
但是你也应该检查文件是否真的损坏了,或者你的下载代码有问题。我不清楚这里有什么问题。您是否下载了一个正常的文件,并发现它在下载过程中总是损坏?或者你想知道如何检测一个损坏的文件而不是下载它?@Beska上传一个文件后,我想检查它是否损坏..它并不总是损坏..显示在使用未被引用的程序集中定义的类型“system.io.packaging.package”时出错。只需添加
windowbase
来自add reference.net
选项卡我必须在我的项目中包括.msi??不,只需在开发机器上安装它,然后将引用添加到DocumentFormat.OpenXml.dll,并在引用的属性中设置Copy local=true。