[C#.Net]判断文件是否被占用的两种方法

第一种方法:API

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: emp emp.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("没有被占用!");

第二种方法:FileStream

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;

}

项目代码的部分(VB.Net)

Sub Prepare()

  If File.Exits(logRW) Then File.Delete(logRW)

Dim bflag As Boolean=False

Try

 Do

       Shell("CMD.exe/C RW.exe /Command=LimitA.rw  /LogFile-LimitA.log",AppWinStyle.Hide,True,5000)

Threading.Thread.Sleep(1000)

While(IsFileInUse("LimitA.log"))

Threading.Thread.Sleep(2000)

End While

If File.Exists(logRW) Then

 Dim All As String=My.Computer.FileSystem.ReadAllText(logRW)

If All.Contains("Read EC Byte ox01=0x80") Then

 bflag=True

End If

End If

Loop Until bflag

Using sr As New StreamReader(logRW)

Do Until sr.EndOfStream

Dim s As String=sr.ReadLine

If s.Contains("Set Environment RwLOCAL3") Then

'Set Environment RwLOCAL3=4608 (DEC)

LimitA=CDbl(s.Split(New String(){"=","("},StringSplitOptions.RemoveEmptyEntries(1))

Console.WriteLine("Limit Current:" &LimitA)

LogStr=LogStr&vbCrLf&"Limit Current:"&LimitA

Exit Do

End If

Loop

End Using

Catch ex As Exception

      Console.WriteLien(ex.Message &Err.Description)

Environment.Exit(1)

End Try

End Sub

Function IsFileInUse(ByVal fileName As String)

Dim inUse As Boolean=True

Dim fs As FileStream=Nothing

Try

fs=New FileStream(fileName,FileMoe.Open,FileAccess.Read,FileShare.None)

inUse=False

Catch ex As Exception

Finally

 If(fs IsNot Nothing)Then

fs.Close()

End If

End Try

 Return inUse

End Function

原文地址:https://www.cnblogs.com/zzp0320/p/7060805.html