今天开发产线测试Tool时发现日志文件会几率性的被占用,上网浏览找到最简单的代码(API或者FileStream),在这里抛砖引玉下。
第一种方法:API
1 using System.IO; 2 using System.Runtime.InteropServices; 3 4 [DllImport("kernel32.dll")] 5 public static extern IntPtr _lopen(string lpPathName, int iReadWrite); 6 7 [DllImport("kernel32.dll")] 8 public static extern bool CloseHandle(IntPtr hObject); 9 10 public const int OF_READWRITE = 2; 11 public const int OF_SHARE_DENY_NONE = 0x40; 12 public readonly IntPtr HFILE_ERROR = new IntPtr(-1); 13 private void button1_Click(object sender, EventArgs e) 14 { 15 string vFileName = @"c: emp emp.bmp"; 16 if (!File.Exists(vFileName)) 17 { 18 MessageBox.Show("文件都不存在!"); 19 return; 20 } 21 IntPtr vHandle = _lopen(vFileName, OF_READWRITE | OF_SHARE_DENY_NONE); 22 if (vHandle == HFILE_ERROR) 23 { 24 MessageBox.Show("文件被占用!"); 25 return; 26 } 27 CloseHandle(vHandle); 28 MessageBox.Show("没有被占用!"); 29 }
第二种方法:FileStream
1 public static bool IsFileInUse(string fileName) 2 { 3 bool inUse = true; 4 5 FileStream fs = null; 6 try 7 { 8 9 fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, 10 11 FileShare.None); 12 13 inUse = false; 14 } 15 catch 16 { 17 } 18 finally 19 { 20 if (fs != null) 21 22 fs.Close(); 23 } 24 return inUse;//true表示正在使用,false没有使用 25 }
项目代码的部分(VB.Net)
1 Sub Prepare() 2 If File.Exists(logRW) Then File.Delete(logRW) 3 Dim bflag As Boolean = False 4 Try 5 Do 6 Shell("CMD.exe /C RW.exe /Command=LimitA.rw /LogFile=LimitA.log", AppWinStyle.Hide, True, 5000) 7 Threading.Thread.Sleep(1000) 8 While (IsFileInUse("LimitA.log")) 9 Threading.Thread.Sleep(2000) 10 End While 11 12 If File.Exists(logRW) Then 13 Dim All As String = My.Computer.FileSystem.ReadAllText(logRW) 14 '检查LogRW的0x01的位置的值是否为0x08 15 If All.Contains("Read EC Byte 0x01 = 0x80") Then 16 bflag = True 17 End If 18 End If 19 Loop Until bflag 20 21 Using sr As New StreamReader(logRW) 22 Do Until sr.EndOfStream 23 Dim s As String = sr.ReadLine 24 If s.Contains("Set Environment RwLOCAL3") Then 25 'Set Environment RwLOCAL3 = 4608 (DEC) 26 LimitA = CDbl(s.Split(New String() {"=", "("}, StringSplitOptions.RemoveEmptyEntries)(1)) 27 Console.WriteLine("Limit Current: " & LimitA) 28 LogStr = LogStr & vbCrLf & "Limit Current: " & LimitA 29 Exit Do 30 End If 31 Loop 32 End Using 33 34 Catch ex As Exception 35 Console.WriteLine(ex.Message & Err.Description) 36 Environment.Exit(1) 37 End Try 38 End Sub 39 40 Function IsFileInUse(ByVal fileName As String) 41 Dim inUse As Boolean = True 42 Dim fs As FileStream = Nothing 43 Try 44 fs = New FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None) 45 inUse = False 46 Catch ex As Exception 47 48 Finally 49 If (fs IsNot Nothing) Then 50 fs.Close() 51 End If 52 End Try 53 Return inUse 54 End Function