判斷文件是否被占用的兩種方法


今天開發產線測試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:\temp\temp.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
復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM