在下面的代码中,我试图检查一个Excel文件是否打开, 如果是那么我想关闭它,当我运行代码时,文件确实是 没有关闭,你能帮忙吗?关闭一个Excel文件,如果发现它已经打开
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(); } } } }
我想帮忙,但是你的代码是不可读的。命名是可怕的,没有评论,和混乱。 – Noctis