检查docx是否已损坏

时间:2015-06-09 12:16:46

标签: c# file openxml

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

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

2 个答案:

答案 0 :(得分:2)

请看这页: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();
    }
}

但您还应该检查文件是否真的损坏,或者您的下载代码是否正常。

答案 1 :(得分:1)

您可以使用OpenXML SDK 2.0中的OpenXmlValidator来验证MS Office文档,例如

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