C#判断文件是否被其他程序打开的几种方法
2021-01-03 12:29
标签:none const 调用dll bool return exist pre static handle 直接使用流判断 调用dll的一些方法 C#判断文件是否被其他程序打开的几种方法 标签:none const 调用dll bool return exist pre static handle 原文地址:https://www.cnblogs.com/zuixime0515/p/13204591.html方法一
public static bool isFileLocked(string pathName)
{
try
{
if (!File.Exists(pathName))
{
return false;
}
using (var fs = new FileStream(pathName, FileMode.Open, FileAccess.Read, FileShare.None))
{
fs.Close();
}
}
catch
{
return true;
}
return false;
}
方法二
public class FileStatus
{
[DllImport("kernel32.dll")]
private static extern IntPtr _lopen(string pathName, int readWrite);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
private const int OF_READWRITE = 2;
private const int OF_SHARE_DENY_NONE = 0x480;
private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
public static bool FileIsOpen(string pathName)
{
if (!File.Exists(pathName))
{
return false;
}
IntPtr handle = _lopen(pathName, OF_READWRITE | OF_SHARE_DENY_NONE);
if (handle == HFILE_ERROR)
{
return true;
}
CloseHandle(handle);
return false;
}
}
上一篇:京东联盟API简易PHP接口类
文章标题:C#判断文件是否被其他程序打开的几种方法
文章链接:http://soscw.com/index.php/essay/39820.html