打开和关闭文件夹中的所有Excel文件

时间:2019-07-16 14:10:00

标签: c#

我正在尝试打开并立即关闭文件夹中的所有.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扩展名重命名该文件。这将导致它损坏。

1 个答案:

答案 0 :(得分:2)

代码中的唯一错误是,您在搜索模式中的* .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));
            }
        }
    }