1、代码
using System; using System.Collections.Generic; using System.IO; using Word = Microsoft.Office.Interop.Word;//nuget 直接搜 namespace ConsoleApp3 { class Program { static void Main(string[] args) { bool isContinue = true; while (isContinue) { Console.WriteLine("请输入文件夹地址,或输入N退出!"); var filePath = Console.ReadLine(); if (filePath == "N") { isContinue = false; continue; } if (!Directory.Exists(filePath)) { Console.WriteLine("路径不存在!!!"); continue; } List<string> fileList = new List<string>(); var dir = new DirectoryInfo(filePath); GetFiles(fileList, dir); if (fileList.Count <= 0) { Console.WriteLine("没有需要转换得文件!"); continue; } foreach (var item in fileList) { Console.WriteLine("处理中。。。"); WordToPDF(item); } Console.WriteLine("完成!!!!"); } } public static bool WordToPDF(string sourcePath) { bool result = false; Word.Application application = new Word.Application(); Word.Document document = null; try { application.Visible = false; document = application.Documents.Open(sourcePath); var p =sourcePath.LastIndexOf("."); string PDFPath = sourcePath.Substring(0, p) + ".pdf";//pdf存放位置 if (!File.Exists(@PDFPath))//存在PDF,不需要继续转换 { document.ExportAsFixedFormat(PDFPath, Word.WdExportFormat.wdExportFormatPDF); } result = true; } catch (Exception e) { Console.WriteLine(e.Message); result = false; } finally { document.Close(); } return result; } /// <summary> /// 获取目录下所有word文件 /// </summary> /// <param name="list"></param> /// <param name="dir"></param> public static void GetFiles(List<string> list, DirectoryInfo dir) { FileInfo[] allFile = dir.GetFiles(); foreach (FileInfo item in allFile) { var extension = item.Extension; if (extension == ".doc" || extension == ".docx") { list.Add(item.FullName); } } DirectoryInfo[] allDir = dir.GetDirectories(); foreach (DirectoryInfo d in allDir) { GetFiles(list,d); } } } }
2、注意事项
需要安装office