C# 检查 Excel 文件是否被锁定的函数实现
以下是一个简单的 C# 函数实现,用于判断一个 Excel 文件是否被锁定:
using System.IO;
public static bool IsExcelFileLocked(string filePath)
{
try
{
using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
fileStream.Close();
}
return false;
}
catch (IOException)
{
return true;
}
}
使用方法:
string filePath = 'C:\path\to\your\file.xlsx';
bool isLocked = IsExcelFileLocked(filePath);
if (isLocked)
{
Console.WriteLine('Excel file is locked');
}
else
{
Console.WriteLine('Excel file is not locked');
}
该函数尝试以读写方式打开文件,如果文件被锁定,则会抛出 IOException 异常,从而判断文件是否被锁定。
原文地址: https://www.cveoy.top/t/topic/o1EO 著作权归作者所有。请勿转载和采集!