Net Core教程

C# 判断文件是否被占用

本文主要是介绍C# 判断文件是否被占用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
using System.IO;
using System.Runtime.InteropServices;

namespace DarkBlue.FileOccupied
{
    public sta class FileHlper
    {

        [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);

        public bool IsOccupied(string fileFullNmae)
        {
            if (!File.Exists(fileFullNmae)) return false;
            IntPtr vHandle = _lopen(fileFullNmae, OF_READWRITE | OF_SHARE_DENY_NONE);
            var flag = vHandle == HFILE_ERROR;
            CloseHandle(vHandle);
            return flag;
        }
    }
}

 

这篇关于C# 判断文件是否被占用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!