本文实例讲述了c#判断本地文件是否处于打开状态的方法。分享给大家供大家参考。具体分析如下:
对于应用程序,有时候可能需要判断某个文件是否已经被打开,也就是指是否被某个流连接着。这在对文件的读写比较频繁的程序中尤为重要,因为一个文件同一时刻只能有一个流连接的。下面的代码也许能有所帮助。
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); 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(); } }
希望本文所述对大家的c#程序设计有所帮助。
如对本文有疑问, 点击进行留言回复!!
使用Visual Studio2019创建C#项目(窗体应用程序、控制台应用程序、Web应用程序)
C#实现获取本地内网(局域网)和外网(公网)IP地址的方法分析
网友评论