Check docx is corrupted or not

我的未来我决定 提交于 2019-12-04 05:10:42

问题


I tried many solution but code is always checking corrupted file and send 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();
}

where path[0] is my docx location..it still read corrupted file and doesnot throw any error..any suggestion plz..


回答1:


Take a look in this page: How to: Validate a word processing document.

Using the Open XML SDK, you can write a code like this:

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

But you should also check if the file was really damaged, or your download code isn't ok.




回答2:


You can use OpenXmlValidator from OpenXML SDK 2.0 to validate MS Office documents, like that

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


来源:https://stackoverflow.com/questions/30731823/check-docx-is-corrupted-or-not

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!