使用 C# 从 DOCX 读取元数据

在当今的数字时代,了解文档中嵌入的隐藏信息对于高效的文档管理和分析至关重要。文档元数据(例如作者身份、创建日期和修订历史记录)可以提供有关文档起源和演变的宝贵见解。在本文中,我们将探讨如何借助元数据库的强大功能,使用 C#** 从 DOCX 读取元数据,使开发人员能够更深入地研究其文档存储库并增强其文档处理工作流程。以下关键步骤和代码示例展示了如何使用 C# **读取 DOCX 的元数据。

使用 C# 从 DOCX 读取元数据的步骤

  1. 设置您的 IDE 以利用 GroupDocs.Metadata for .NET 检索 DOCX 元数据信息
  2. 创建 Metadata 类的实例,将 DOCX 文件的文件路径作为参数传递给构造函数
  3. 创建谓词来检查所有检索到的元数据属性
  4. Metadata.FindProperties 方法提供谓词
  5. 迭代检索到的属性

无论是自动化文档分类、在文档存储库中实现搜索功能,还是确保符合组织标准,在 C# 中提取 DOCX 元数据 的能力都为开发人员带来了多种可能性。只要安装了 .NET,遵守给定的说明就可以与 Windows、macOS 和 Linux 等广泛使用的操作系统兼容。此过程不需要安装其他软件。一旦您设置了推荐的库并相应地调整了文件路径,将以下代码合并到您的项目中应该会顺利进行,不会出现任何问题。

使用 C# 从 DOCX 读取元数据的代码

using GroupDocs.Metadata;
using GroupDocs.Metadata.Common;
using GroupDocs.Metadata.Tagging;
using System.Text.RegularExpressions;
namespace ReadMetadataFromDOCXUsingCSharp
{
internal class Program
{
static void Main(string[] args)
{
// Set License to avoid the limitations of Metadata library
License lic = new License();
lic.SetLicense(@"GroupDocs.Metadata.lic");
// Pass absolute or relative path of document to Metadata's constructor
using (Metadata metadata = new Metadata(@"input.docx"))
{
if (metadata.FileFormat != FileFormat.Unknown && !metadata.GetDocumentInfo().IsEncrypted)
{
Console.WriteLine();
// Fetch all metadata properties that fall into a particular category
var properties = metadata.FindProperties(p => p.Tags.Any(t => t.Category == Tags.Content));
Console.WriteLine("The metadata properties describing some characteristics of the file content: title, keywords, language, etc.");
foreach (var property in properties)
{
Console.WriteLine("{0} = {1}", property.Name, property.Value);
}
// Fetch all properties having a specific type and value
var year = DateTime.Today.Year;
properties = metadata.FindProperties(p => p.Value.Type == MetadataPropertyType.DateTime &&
p.Value.ToStruct(DateTime.MinValue).Year == year);
Console.WriteLine("All datetime properties with the year value equal to the current year");
foreach (var property in properties)
{
Console.WriteLine("{0} = {1}", property.Name, property.Value);
}
// Fetch all properties whose names match the specified regex
const string pattern = "^author|company|(.+date.*)$";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
properties = metadata.FindProperties(p => regex.IsMatch(p.Name));
Console.WriteLine("All properties whose names match the following regex: {0}", pattern);
foreach (var property in properties)
{
Console.WriteLine("{0} = {1}", property.Name, property.Value);
}
}
}
}
}
}

总之,从 DOCX 读取元数据使开发人员能够更深入地了解其文档集合。通过遵循本文中概述的步骤并利用提供的代码示例,您可以无缝获取 C# 中的 DOCX 元数据,从而更好地组织、分析和管理文档。尝试不同的元数据属性并探索该库,以进一步扩展 C# 中的文档处理功能。恭喜!您现在已经能够熟练使用 C# 提取 DOCX 元数据。

在之前的对话中,我们提供了有关使用 C# 检索文档信息的详细教程。为了更深入地理解这个主题,我们建议您查阅我们关于如何使用C#获取文档信息的详细指南。

 简体中文