Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 4.0 C#打开Word文档前测试其是否有效_C# 4.0 - Fatal编程技术网

C# 4.0 C#打开Word文档前测试其是否有效

C# 4.0 C#打开Word文档前测试其是否有效,c#-4.0,C# 4.0,我正在使用C#和Microsoft.Office.Interop.Word处理Microsoft Word文档。问题是,当我将一个图像重命名为文件扩展名.doc,然后按如下方式调用com对象时,它会挂起。在尝试打开文件之前,必须有一种方法来测试该文件是否是有效的word文档。有人有答案吗 ApplicationClass.Documents.Open(ref path, ref missing, ref readOnly,

我正在使用C#和Microsoft.Office.Interop.Word处理Microsoft Word文档。问题是,当我将一个图像重命名为文件扩展名.doc,然后按如下方式调用com对象时,它会挂起。在尝试打开文件之前,必须有一种方法来测试该文件是否是有效的word文档。有人有答案吗

ApplicationClass.Documents.Open(ref path,
                                ref missing, ref readOnly,
                                ref missing, ref missing, ref missing,
                                ref missing, ref missing, ref missing,
                                ref missing, ref missing, ref isVisible,
                                ref missing, ref missing, ref missing);

您可以检查文件中的前几个字节,查看-尤其是关于FIB(文件信息块)内容的部分。docx文件当然需要不同的处理。

经过一些测试后,我决定使用Aspose:


事实证明,这是非常强大和简单的使用。如果文档格式不正确,则会引发异常,可以捕获并处理该文档。

您可以检查if文档是否存在

(System.IO.File.Exists((字符串)文件名)) {

} 由于路径是一个字符串,您可以在最后3-4个符号中使用子字符串。 或者可以使用分隔符“.”将其拆分 这应该给你第一部分和最后一部分