In the following code i am trying to check if an Excel file is open , if it is then I want to close it , when i run the code , the file does not get closed , can you please help?
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(); } } } }