我正在尝试打开并立即关闭文件夹中的所有.xls文件,以确定哪些文件已损坏(如果我手动打开已损坏的文件,系统将显示一条消息,指出该文件已损坏且无法打开)。文件夹中有数千个文件。这是我所拥有的,但似乎不起作用。我将它放在try catch块中,但没有显示任何错误,也没有发生任何事情。
public void OpenXLSFiles()
{
string[] folder = Directory.GetFiles(@"c:\pricelist\", " *.xls");
foreach (string file in folder)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbv = excel.Workbooks.Open(file);
wbv.Close();
excel.Quit();
Marshal.ReleaseComObject(wbv);
Marshal.ReleaseComObject(excel);
}
}
若要创建损坏的excel文件,请创建一个新的xlsx文件,然后在其中键入一些文本。将该文件保存到您的计算机,并仅使用.xls扩展名重命名该文件。这将导致它被损坏。
发布于 2019-07-16 22:32:15
代码中唯一的错误是在搜索模式中的*.xls前面加了一个额外的空格。所以,它甚至不会尝试打开任何文件。请使用下面的代码标记损坏的文件。
public static void OpenXLSFiles()
{
string[] folder = Directory.GetFiles(@"d:\pricelist\", "*.xls");
foreach (string file in folder)
{
try
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wbv = excel.Workbooks.Open(file);
wbv.Close();
excel.Quit();
Marshal.ReleaseComObject(wbv);
Marshal.ReleaseComObject(excel);
}
catch (Exception)
{
Console.WriteLine(string.Format("File is corrupt : {0}", file));
}
}
}
https://stackoverflow.com/questions/57059257
复制相似问题