如果发现已经打开,请closuresExcel文件

在下面的代码中,我试图检查一个Excel文件是否打开,如果是那么我想closures它,当我运行的代码,该文件没有被closures,你能帮助吗?

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; using Microsoft.Office.Interop.Excel; using Excel = Microsoft.Office.Interop.Excel; namespace CloseIfFileOpen { class Program { public static void Main() { Excel.Application oApp; Excel.Workbook oBook; oApp = new Excel.Application(); oBook =oApp.Workbooks.Add(@"C:\Users\user\Documents\WEF\Excel\Example.xlsx"); string filePath; filePath = @"C:\Users\user\Documents\WEF\Excel\Example.xlsx"; try { using (File.Open(filePath, FileMode.Open)) { } } catch (IOException e) { var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1); //return errorCode == 32 || errorCode == 33; MessageBox.Show("the file is unavailable now"); oBook.Save(); oBook.Close(); oApp.Quit(); } } } } 

我是否正确地假设你想检查文件是否被另一个进程使用,如果是,closures它? 因为我不认为有什么办法可以在Windows中做到这一点,你只能closures自己的文件的使用。 可能有办法通过使用Win32 API来强制解锁文件,但是没有任何内容被构build到C#中。 调用closures文件只会closures您自己对文件的使用,不会影响其他进程。

我正在使用这种方法来检查,如果我可以打开一个文件,如果是的话,那么这样做,如果不是,那么不要用参数path设置为Excel表格path

  private Microsoft.Office.Interop.Excel.Application appExcel; private Workbook newWorkbook = null; private _Worksheet objsheet = null; public void excel_init(String path) { appExcel = new Microsoft.Office.Interop.Excel.Application(); if (System.IO.File.Exists(path)) { // then go and load this into excel newWorkbook = appExcel.Workbooks.Open(path, true, true); objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet; } else { Console.WriteLine("Unable to open workbook"); System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel); appExcel = null; } } 

您并不是说要独占访问该文件。 似乎不太可能,但也许Excel不会locking该文件,以便其他进程可以在读取模式下打开该文件。 也许你的文件打开行应该是:

using (File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None)) { }

这段代码,当然,将帮助你检查文件是否打开或不(我检查了这个代码为Excel文件)

 private bool check_file_oppen(string check) {//where string check is the path of required file try { Stream s = File.Open(check, FileMode.Open, FileAccess.Read, FileShare.None); s.Close(); MessageBox.Show("FILE IS NOT OPEN"); return true; } catch (Exception) { MessageBox.Show("FILE IS OPEN"); return false; } } 

现在,“如果这个excel文件是开放的,那么如何closures它?” 是我仍然在寻找的问题,…………

如果你find答案,请与我分享……………

谢谢。

方舟。

  foreach (var process in Process.GetProcessesByName("EXCEL")) { process.Kill(); }