C# 判断文件是否被占用的两种方法

C# 判断文件是否被占用的两种方法,第1张

1.第一种方法:using System.Runtime.InteropServices[DllImport(kernel32.dll)]public static extern IntPtr _lopen(string lpPathName, int iReadWrite)[DllImport(kernel32.dll)]public static extern bool CloseHandle(IntPtr hObject)public const int OF_READWRITE = 2public const int OF_SHARE_DENY_NONE = 0x40public readonly IntPtr HFILE_ERROR = new IntPtr(-1)private void button1_Click(object sender, EventArgs e){string vFileName = @c:\temp\temp.bmpif (!File.Exists(vFileName)){MessageBox.Show(文件都不存在!)return}IntPtr vHandle = _lopen(vFileName, OF_READWRITE | OF_SHARE_DENY_NONE)if (vHandle == HFILE_ERROR){MessageBox.Show(文件被占用!)return}CloseHandle(vHandle)MessageBox.Show(没有被占用!)}第二种方法:public static bool IsFileInUse(string fileName){bool inUse = trueFileStream fs = nulltry{fs = new FileStream(fileName, FileMode.Open, FileAccess.Read,FileShare.None)fs.Close()}return inUse//true表示正在使用,false没有使用}

这个需要对文件加锁才能,可以用fcntl函数实现

int lock(const char * filepath )

{

int fd = 0

struct flock flock

memset( &flock, 0, sizeof(flock) )

fd = open( filepath, O_RDWR,S_IRUSR|S_IWUSR )

if ( fd <0 )

{

printf("open error!\n")

return ( -1 )

}

flock.l_type = F_WRLCK

flock.l_whence = SEEK_SET

flock.l_start = 100000

flock.l_len = 0

if ( fcntl( fd, F_SETLK, &flock ) ) //加锁,如果失败则等待10秒

{

printf("cannot set lock\n")

printf("the process will retry after 10 seconds\n")

sleep(10) //不同版本的sleep单位可能不一样,有的是秒有的是毫秒,你自己看着改

if ( fcntl( fd, F_SETLK, &flock ) ) //加锁,如果失败则退出

return( -1 )

}

return( 0 )

}

后面的你懂吧

string fileName = @"c:\aaa.doc"//要检查被那个进程占用的文件

Process tool = new Process()

tool.StartInfo.FileName = "handle.exe"

tool.StartInfo.Arguments = fileName+" /accepteula"

tool.StartInfo.UseShellExecute = false

tool.StartInfo.RedirectStandardOutput = true

tool.Start()

tool.WaitForExit()

string outputTool = tool.StandardOutput.ReadToEnd()

string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)"

foreach(Match match in Regex.Matches(outputTool, matchPattern))

{

Process.GetProcessById(int.Parse(match.Value)).Kill()

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11599016.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存