我有.docx
文件,其中只为MS Office文件指定了自定义属性。 如何在没有Office.Interop的情况下阅读'Extended'MS Word文件标签?
如果我试图打开电脑相同的文件没有安装MS办公室再有就是在文件的详细信息标签不标签属性。
我需要在我的c#代码中阅读Tags
。
我试过this solution和retieve Tags
索引为18
。然后我用下面的代码:
public class TagsReader : ITagsReader
{
private const int keywordsIndex = 18;
public string Read(string filePath)
{
var fullPath = Path.GetFullPath(filePath);
var directoryName = Path.GetDirectoryName(fullPath);
Folder dir = GetShell32Folder(directoryName);
var fileName = Path.GetFileName(fullPath);
FolderItem item = dir.ParseName(fileName);
return dir.GetDetailsOf(item, keywordsIndex);
}
private Folder GetShell32Folder(string folderPath)
{
var shellAppType = Type.GetTypeFromProgID("Shell.Application");
var shell = Activator.CreateInstance(shellAppType);
return (Folder)shellAppType.InvokeMember("NameSpace",
BindingFlags.InvokeMethod, null, shell, new object[] { folderPath });
}
}
但它并不适用于电脑没有安装微软Office工作。它仅适用于.doc
文件,但不适用于.docx
。现在我用Inerop
基础的解决方案是不是稳定的,资源密集型的,需要安装微软Office服务器:
public class WordTagsReader : ITagsReader
{
private readonly string[] availableFileExtensions = { ".docx" };
public string Read(string filePath)
{
var fileExtension = Path.GetExtension(filePath);
if (!availableFileExtensions.Contains(fileExtension))
return null;
dynamic application = null;
dynamic document = null;
var tags = string.Empty;
try
{
var typeWord = Type.GetTypeFromProgID("Word.Application");
application = Activator.CreateInstance(typeWord);
application.Visible = false;
application.DisplayAlerts = false;
var fullFilePath = Path.GetFullPath(filePath);
document = application.Documents.Open(fullFilePath);
tags = document.BuiltInDocumentProperties["Keywords"].Value;
}
finally
{
if (document != null)
{
document.Close();
document = null;
}
if (application != null)
{
application.Quit();
application = null;
}
}
return tags;
}
}
该代码可以崩溃,不时和左运行这需要资源的MS Word的实例,块文件。我有很多处理程序在同一时间工作,然后我无法从正常工作和清洁资源中分离“左”实例。
这是搜索备用解决方案的原因。有没有方法来阅读特定(自定义)属性,如Tags
而不使用Office.Interop
?
TY到所有的答案。 –