我有.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到所有的答案。 –