本文介绍了检查docx是否损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

其中path [0]是我的docx位置.它仍然读取损坏的文件,并且没有引发任何错误.

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

推荐答案

在此页中查看:如何:验证文字处理文档.

使用 Open XML SDK ,您可以编写如下代码:

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.

这篇关于检查docx是否损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-23 09:06