C# 如何判断一个文件是否被占用

 时间:2024-10-14 16:01:15

1、using System.IO;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("没有被占用!");}

2、public static bool IsFileInUse(string fileName){ bool inUse = true; FileStream fs = null; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None); inUse = false; } catch { } finally { if (fs != null) fs.Close(); } return inUse;//true表示正在使用,false没有使用}

  • Windows Server 2008操作系统如何新建域组帐户
  • editplus文本替换方法
  • 易语言“程序延时”命令问题的解决定时关机软件
  • 易语言怎么计算加法?
  • 如何在Windows10系统通过freeFTPd搭建FTP服务器
  • 热门搜索
    油炸糖糕的做法 鱼丸的家常做法 圭怎么读 保险怎么买 转正申请书怎么写 微信怎么注册 玫瑰花怎么养才不会枯萎 苹果12怎么关机 蟹炒年糕的做法 鲅鱼的做法