+-
c#-在打开或启动之前检查excel文件是否可用
好的,所以这是问题所在,我使用了using(connection …. blah blah)的连接,然后在我的using块结束后,我想像这样启动excel应用程序:System.Diagnostics.Process.Start(excelFile);

有时,这可以正常工作……有时我的计算机运行得太快,并且在文件完全关闭之前,或者在连接完全终止之前,诸如此类,上面的语句被取消,Excel打开并说它无法访问该文件.

这会断断续续发生,如果我暂停它,它会更频繁地工作,但是我需要一种方法来检查在访问文件之前是否能够访问该文件.

这不会引发异常,因此捕获异常不是一种选择

我努力了:

connection.Close();
connection.Dispose();
GC.Collect();

其中没有一个起作用.

我知道任何检查都将使大多数likley都具有返回文件可用的可能性,然后在公开声明被某人使用的文件免除之前,这很好.只需要一种检查方法.

好的,我尝试了这个:

Microsoft.Office.Interop.Excel.Application _app =
                          new Microsoft.Office.Interop.Excel.Application();

        try
        {
            Workbook wbook = _app.Workbooks.Open(excelFile,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        }
        catch (COMException ex)
        {
            //The file can't be opened in Excel
        }
        finally
        {
            //close the workbook and release the resources (GC.Collect() et al as usual)
            _app.Workbooks.Close();
            GC.Collect();

        }
        System.Diagnostics.Process.Start(excelFile);

我经历了捕获异常,然后转到启动命令,其中excel告诉我它“无法访问’fileName’”

最佳答案
尝试使用此功能来检查文件是否仍然打开:

public bool IsFileOpen(string path)
{
    FileStream fs = null;
    try
    {
        fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None);
        return false;
    }
    catch(IOException ex)
    {
        return true;
    }
    finally
    {
        if (fs != null)
            fs.Close();
    }
}
点击查看更多相关文章

转载注明原文:c#-在打开或启动之前检查excel文件是否可用 - 乐贴网