使用EPPlus读取Excel时遇~$临时文件报错:不是有效Package文件
解决方案:跳过Excel临时锁定文件
遇到的~$开头文件是Excel在打开时生成的隐藏临时锁定文件,这类文件并非完整的Excel包,所以会触发The file is not a valid Package file错误。由于你无法修改文件或文件夹,最直接的解决方式是在读取阶段过滤这类文件:
方法1:获取文件列表时直接过滤
通过LINQ筛选掉以~$开头的文件,修改文件获取逻辑:
using System.Linq; // 需要引入LINQ命名空间 string[] arrStatements = Directory.GetFiles(localPath, "*.xlsx") .Where(filePath => !Path.GetFileName(filePath).StartsWith("~$")) .ToArray();
方法2:遍历过程中跳过临时文件
如果不使用LINQ,也可以在循环内判断文件名并跳过:
string[] arrStatements = Directory.GetFiles(localPath, "*.xlsx"); foreach (var statement in arrStatements) { string fileName = Path.GetFileName(statement); // 跳过~$开头的临时文件 if (fileName.StartsWith("~$")) continue; FileInfo excelFilee = new FileInfo(statement); processedStage = excelFilee.ToString(); using (ExcelPackage excell = new ExcelPackage(excelFilee)) { // 你的Excel处理逻辑 } }
这两种方案都不需要修改文件或文件夹权限,仅在代码层面拦截无效的临时文件,就能避免触发错误。
内容的提问来源于stack exchange,提问作者NootNoobJoe
相关产品推荐
相关产品推荐

