在打开或启动之前检查是否有excel文件可用

好,所以这里的问题,我使用连接使用(连接….等等等等等),然后在我的使用块结束后,我想开始像这样的Excel应用程序:System.Diagnostics.Process.Start(excelFile);

这有效,有时,有时,我的电脑运行太快,文件完全closures之前,或连接完全终止,或类似的东西,上述语句是exicuted和Excel打开,并表示无法访问该文件。

这种情况会发生,如果我暂停,它会更频繁地工作,但我需要一种方法来检查,如果我能访问该文件之前,我访问它。

这不会抛出exception,因此捕捉exception不是一个选项

我努力了:

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

其中没有工作。

我知道任何支票将最有可能返回的文件是可用的,然后才可以打开文件正在使用的文件被人使用,这很好。 只需要一个方法来检查。

好吧,我试过这个:

 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); 

我经历了捕捉exception,然后进入开始命令,在Excel中告诉我它不能访问'fileName'“

试试这个function来检查文件是否仍然打开:

 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(); } } 

我假设,当你正在写入文件,你可以很容易地得到它的文件大小。 你试过比较两个吗?

 while (fileSize != new FileInfo(excelFile).Length) { Thread.Sleep(1000); } System.Diagnostics.Process.Start(excelFile); 

如果文件没有正确写入,您可能需要放置一个计数器,以免永远睡眠。 不知道这是否会奏效,但我猜这值得一试。

查看文件是否有效在Excel中打开的选项是使用主互操作程序集 :

 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) } //The file can be opened in Excel if there wasn't a caught exception. //You can wrap the above in a loop to test more than once as per the other answer 

但是,无论如何,find一个好的方法来同步你的阅读材料还是更好的。 也许如果你与写作部分分享代码,你可以得到更好的build议。

解决scheme1:你可以试试

 File.Move(sourceFilename, destinationFilename) 

为您要打开的文件。 如果没有exception,只需将文件移回原始源。

这个解决scheme的一个缺点是它也会抛出一个exception,如果该文件被任何其他进程读取。

解决scheme2:

  FileStream stream = File.OpenWrite("yourfilename"); stream.Close(); 

这应该只检查文件是否可写。

有了这些解决scheme,您不必将依赖项添加到Excel,并且适用于每种文件types。

您可以使用FileSystemWatcher类来订阅文件系统事件,包括文件更改。

当更改事件已经触发,我想可以安全地打开文件。 尽pipe如此,另外检查文件是否被其他进程重新locking,仍然值得一试。