C# 试图通过Microsoft Word 11.0对象库使用Microsoft.Office.Interop.Word会导致编译错误
Env:Windows 10 64位,Visual Studio express 2013。我已经安装了microsoft office 2013和2003。并且已经添加了C# 试图通过Microsoft Word 11.0对象库使用Microsoft.Office.Interop.Word会导致编译错误,c#,visual-studio-2012,office-interop,C#,Visual Studio 2012,Office Interop,Env:Windows 10 64位,Visual Studio express 2013。我已经安装了microsoft office 2013和2003。并且已经添加了Microsoft Office 11.0对象库和Microsoft Word 11.0对象库引用。但不起作用。 我尝试过,如果我将Microsoft Word 11.0对象库更改为Microsoft Word 15.0对象库,一切正常。但我需要为Word 2003工作,那么,我该怎么办 代码: 使用系统; 使用System
Microsoft Office 11.0对象库
和Microsoft Word 11.0对象库
引用。但不起作用。
我尝试过,如果我将Microsoft Word 11.0对象库
更改为Microsoft Word 15.0对象库
,一切正常。但我需要为Word 2003工作,那么,我该怎么办
代码:
使用系统;
使用System.IO;
使用System.Collections.Generic;
使用系统文本;
使用Word=Microsoft.Office.Interop.Word;
名称空间readDOC{
班级计划{
静态void Main(字符串[]参数){
字符串cd=Directory.GetCurrentDirectory();
Word.Application Word=新单词.Application();
List dirs=新列表();
foreach(Directory.GetFiles(@“.”,*.doc?”)中的字符串dir){
if(dir.IndexOf('~')==-1){
直接加(cd+直接子串(1));
}
}
foreach(dirs中的字符串fn){
Word.Documents=Word.Documents.Open(fn);
试一试{
docs.Protect(Word.WdProtectionType.wdAllowOnlyReading);
WriteLine(@“OK:{0}.”,fn);
}捕获(例外e){
WriteLine(@“不正常:{0}.”,fn);
}最后{
docs.Close();
}
}
word.Quit();
Console.WriteLine(“按任意键完成”);
Console.ReadLine();
}
}
}
在回顾了这个问题之后,我认为这是因为您没有使用互操作(扩展)
由于要添加2003,请确保将构建平台目标设置为x86。2003年没有x64支持。那是我的猜测。我不能测试2003,因为这是我的工作机器
我希望我的建议能为您指明正确的方向。什么不起作用?错误是什么?请发布完整的异常文本,即使用
exception.ToString()
。据我们所知,您可能会收到一个“未找到文件”错误。顺便说一句,您无法打开特定版本,如所示。这不是word特有的,这只是COM/OLE的工作方式。每个COM应用程序都会注册所有以前的接口,因此,当您要求11.0时,您将获得该应用程序的注册表,即Word 2013。您为什么要与2003进行互操作?生成doc
而不是docx
文件时,您不需要它-您可以通过互操作指定要保存到的格式。此外,很少有人仍然使用旧格式<代码>docx已经有7年历史了。您可以使用OpenXMLSDK生成docx
文件,而无需Wordinstalled@Panagiotis看我的第一张照片。使用word=Microsoft.Office.Interop.word的第行的单词Interop
下面有一条红线,这意味着Interop
不是Microsoft.Office的成员,无需构建即可使错误弹出并粘贴到此处。@Panagiotis Kanavos我需要编写一个程序,使数百个.doc
和.docx
文件在windows xp(sp1或sp2或sp3)下只读,如果我与2013进行互操作,它显然不起作用。
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using Word = Microsoft.Office.Interop.Word;
namespace readDOC {
class Program {
static void Main(string[] args) {
string cd = Directory.GetCurrentDirectory();
Word.Application word = new Word.Application();
List<string> dirs = new List<string>();
foreach (string dir in Directory.GetFiles(@".", "*.doc?")) {
if (dir.IndexOf('~') == -1) {
dirs.Add(cd + dir.Substring(1));
}
}
foreach (string fn in dirs) {
Word.Document docs = word.Documents.Open(fn);
try {
docs.Protect(Word.WdProtectionType.wdAllowOnlyReading);
Console.WriteLine(@"OK:{0}.", fn);
} catch (Exception e) {
Console.WriteLine(@"NOT OK:{0}.", fn);
} finally {
docs.Close();
}
}
word.Quit();
Console.WriteLine("Press any key to finish");
Console.ReadLine();
}
}
}