using System; using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; namespace FindConnectionInDB { class Program { static void Main(string[] args) { string xlsfile = @"c:\temp\book1.xlsx"; Program p = new Program(); bool ret = p.CheckDbConnectionInExcel(xlsfile); Console.WriteLine("Has DB Connection : {0}", ret); } public bool CheckDbConnectionInExcel(string excelFile) { bool hasDBConnection = false; Excel.Application excelApp = null; Excel.Workbook wb = null; try { excelApp = new Excel.Application(); wb = excelApp.Workbooks.Open(excelFile); for (int i = 1; i <= wb.Connections.Count; i++) { if (wb.Connections[i].Type == Excel.XlConnectionType.xlConnectionTypeOLEDB || wb.Connections[i].Type == Excel.XlConnectionType.xlConnectionTypeODBC) { hasDBConnection = true; break; } } wb.Close(true); excelApp.Quit(); } finally { ReleaseExcelObject(wb); ReleaseExcelObject(excelApp); } return hasDBConnection; } private void ReleaseExcelObject(object obj) { try { if (obj != null) { Marshal.ReleaseComObject(obj); obj = null; } } catch (Exception ex) { obj = null; throw ex; } finally { GC.Collect(); } } } }
One thing to note is that you need to release Excel object by using Marshal.ReleaseComObject() so that in any case your Excel process can be disposed.
No comments:
Post a Comment