检查docx是否损坏

Check docx is corrupted or not

我尝试了很多解决方案,但代码总是检查损坏的文件并发送 true

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位置..它仍然读取损坏的文件并且没有抛出任何错误..任何建议plz..

您可以使用 OpenXML SDK 2.0 中的 OpenXmlValidator 来验证 MS Office 文档,就像那样

OpenXmlValidator validator = new OpenXmlValidator();
bool isValid=validator.Validate(WordprocessingDocument.Open("InvalidFile.docx", true)).Count()==0

查看此页面:How to: Validate a word processing document

使用Open XML SDK,你可以写这样的代码:

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();
    }
}

不过你也应该看看是不是文件真的损坏了,或者是你的下载码不对。