如何在程序中以不同扩展名定位文件?以docx当作zip读取为例
直接读取DOCX文件(作为ZIP)获取字数统计
完全不用改扩展名,DOCX本身就是符合ZIP规范的归档文件,直接用ZipFile或ZipArchive就能读取。你之前的代码没成功,大概率是路径没写对,或者没定位到正确的docProps/app.xml文件。
下面给两种可行的实现方式:
方法1:提取ZIP内容后读取XML
直接把DOCX路径传给ZipFile.ExtractToDirectory,之后去提取目录里找docProps/app.xml解析即可:
using System; using System.IO; using System.IO.Compression; using System.Xml.Linq; class Program { static void Main(string[] args) { string docxPath = @".\your-file.docx"; string extractPath = @".\extract"; // 直接提取DOCX(当作ZIP)到指定目录 ZipFile.ExtractToDirectory(docxPath, extractPath); // 定位到app.xml文件 string appXmlPath = Path.Combine(extractPath, "docProps", "app.xml"); if (File.Exists(appXmlPath)) { // 解析XML获取字数 XElement appXml = XElement.Load(appXmlPath); // 注意命名空间,app.xml里的节点属于指定格式的命名空间 XNamespace ns = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"; string wordCount = appXml.Element(ns + "Words")?.Value; Console.WriteLine($"文档字数:{wordCount}"); } else { Console.WriteLine("未找到app.xml文件"); } } }
方法2:不提取文件,直接在ZIP归档中读取XML
这种方式更高效,不用生成临时文件:
using System; using System.IO; using System.IO.Compression; using System.Xml.Linq; class Program { static void Main(string[] args) { string docxPath = @".\your-file.docx"; using (ZipArchive archive = ZipFile.OpenRead(docxPath)) { // 找到ZIP里的docProps/app.xml条目 ZipArchiveEntry appXmlEntry = archive.GetEntry("docProps/app.xml"); if (appXmlEntry != null) { // 读取条目内容 using (StreamReader reader = new StreamReader(appXmlEntry.Open())) { XElement appXml = XElement.Parse(reader.ReadToEnd()); XNamespace ns = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"; string wordCount = appXml.Element(ns + "Words")?.Value; Console.WriteLine($"文档字数:{wordCount}"); } } else { Console.WriteLine("ZIP归档中未找到app.xml"); } } } }
注意事项
- .NET Core/.NET 5+默认已包含
System.IO.Compression相关程序集,.NET Framework可能需要手动添加引用 app.xml里的节点带有固定命名空间,解析时必须指定,否则会找不到Words统计节点
内容的提问来源于stack exchange,提问作者TryingToLearn
相关产品推荐
相关产品推荐

