C# 判断文件是否被占用的两种方法
2个回答
展开全部
其他知友问过,大神解决方法如下:
第一种方法:
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 = 2;
public const int OF_SHARE_DENY_NONE = 0x40;
public readonly IntPtr HFILE_ERROR = new IntPtr(-1);
private void button1_Click(object sender, EventArgs e){string vFileName = @c:\temp\temp.bmp;
if (!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 = true;
FileStream fs = null;try{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read,
FileShare.None);
fs.Close();}return inUse;//true表示正在使用,false没有使用}
第一种方法:
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 = 2;
public const int OF_SHARE_DENY_NONE = 0x40;
public readonly IntPtr HFILE_ERROR = new IntPtr(-1);
private void button1_Click(object sender, EventArgs e){string vFileName = @c:\temp\temp.bmp;
if (!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 = true;
FileStream fs = null;try{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read,
FileShare.None);
fs.Close();}return inUse;//true表示正在使用,false没有使用}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询