COMException尝试打开特定的Word文件时

时间:2016-09-28 07:28:38

标签: c# ms-office

我想打开/阅读我的docx文档。到目前为止一切正常但是如果文件名包含“_”,“”,“ - ”则会出现一些异常,因为出于某种原因而引发异常:

其他信息:抱歉,我们找不到您的文件。它是否可能被移动,重命名或删除?

到目前为止我在做什么:

 string path = "C:/Users/Hans/Rep";
            foreach (string file in Directory.EnumerateFiles(path, "*.docx"))
            {
                {
                    //Open the doc File
                    var fileInfo = new FileInfo(file);

                    if (!fileInfo.Name.StartsWith("~$"))
                    {
                        var wordApplication = new Microsoft.Office.Interop.Word.Application();
                        var document = wordApplication.Documents.Open(file);
                        //Set paper Size
                        document.PageSetup.PaperSize = WdPaperSize.wdPaperA4;

尝试打开文件时出现崩溃。是否需要设置一些特定的参数/参数?!

1 个答案:

答案 0 :(得分:0)

我认为这可能会改变,具体取决于您使用的Word版本。我必须提供很多参数来打开/关闭应用程序和文档。我不得不从你的部分代码中改变一些东西。但是下面的代码将打开Word Doc。希望这会有所帮助。

object missing = System.Reflection.Missing.Value;
object readOnly = false;
object isVisible = true;
object doNotSaveChanges = Word.WdSaveOptions.wdDoNotSaveChanges;
Object saveChanges = Word.WdSaveOptions.wdPromptToSaveChanges;

public Form1()
{
  InitializeComponent();

  string path = "C:/Test";

  Word._Application wordApplication = new Microsoft.Office.Interop.Word.Application();
  foreach (string file in Directory.GetFiles(path, "*.docx"))
  {
    {
      //Open the doc File
      FileInfo fileInfo = new FileInfo(file);
      Object fileName = fileInfo.FullName;

      if (!fileInfo.Name.StartsWith("~$"))
      {
        Word._Document document = wordApplication.Documents.Open(ref fileName, 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, ref missing);
        //Set paper Size
        document.PageSetup.PaperSize = WdPaperSize.wdPaperA4;



      }
    }
  }
  document.Close(ref doNotSaveChanges, ref missing, ref missing);
  wordApplication.Quit(ref saveChanges, ref missing, ref missing);
}