C# 检查 Excel 文件是否被锁定的函数实现
以下是一个 C# 的函数实现,用于检查 Excel 文件是否被锁定:
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
public static bool IsExcelFileLocked(string filePath)
{
bool isLocked = false;
// 创建 Excel 应用程序
Excel.Application excelApp = new Excel.Application();
try
{
// 打开 Excel 文件
Excel.Workbook workbook = excelApp.Workbooks.Open(filePath, ReadOnly: true);
// 关闭 Excel 文件
workbook.Close(false);
}
catch (IOException)
{
// 如果捕获到 IOException 异常,则说明文件被锁定
isLocked = true;
}
finally
{
// 退出 Excel 应用程序并释放资源
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
excelApp = null;
}
return isLocked;
}
使用示例:
string filePath = 'path_to_excel_file';
bool isLocked = IsExcelFileLocked(filePath);
if (isLocked)
{
Console.WriteLine('Excel 文件被锁定');
}
else
{
Console.WriteLine('Excel 文件未被锁定');
}
请注意,此函数使用了 Microsoft.Office.Interop.Excel 库,因此您需要在项目中添加对'Microsoft.Office.Interop.Excel'的引用。另外,由于 Excel 应用程序是一个 COM 对象,需要在使用完毕后手动释放资源,以避免内存泄漏。
原文地址: https://www.cveoy.top/t/topic/o1EA 著作权归作者所有。请勿转载和采集!