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 )
}
后面的你懂吧
评论列表(0条)