如何判断文件是否在占用?
使用托管方法来实现。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
namespace ALU.C0370A.SimuDID.Common
{
public class FileStatus
{
[DllImport("kernel32.dll")]
private static extern IntPtr _lopen(string lpPathName, int iReadWrite);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
private const int OF_READWRITE = 2;
private const int OF_SHARE_DENY_NONE = 0x40;
private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
//Judge whether the file is handled by process now
public static int FileIsOpen(string fileFullName)
{
if (!File.Exists(fileFullName))
{
return -1;
}
IntPtr handle = _lopen(fileFullName, OF_READWRITE | OF_SHARE_DENY_NONE);
if (handle == HFILE_ERROR)
{
return 1;
}
CloseHandle(handle);
return 0;
}
}
}
测试代码:
class Program { static void Main(string[] args) { string testFilePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"testOpen.txt"; FileStream fs = new FileStream(testFilePath, FileMode.OpenOrCreate, FileAccess.Read); BinaryReader br = new BinaryReader(fs); br.Read(); Console.WriteLine("文件被打开"); int result =FileStatus.FileIsOpen(testFilePath); Console.WriteLine(result); br.Close(); Console.WriteLine("文件被关闭"); result = FileStatus.FileIsOpen(testFilePath); Console.WriteLine(result); Console.ReadLine(); } }
结果如下:


浙公网安备 33010602011771号