using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
namespace FileStatusTest
{
public class FileStatusHelper
{
[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 static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
/// <summary>
/// 查看文件是否被占用
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static bool IsFileOccupied(string filePath)
{
IntPtr vHandle = _lopen(filePath, OF_READWRITE | OF_SHARE_DENY_NONE);
CloseHandle(vHandle);
return vHandle == HFILE_ERROR ? true : false;
}
}
}
本文介绍了一个使用C#编写的实用方法,用于检查文件是否正在被其他进程占用。通过调用kernel32.dll中的_lopen和CloseHandle函数,此方法能够在Windows环境下有效地判断文件状态。
1544

被折叠的 条评论
为什么被折叠?



