今天开发产线测试Tool时发现日志文件会几率性的被占用,上网浏览找到最简单的代码(API或者FileStream),在这里抛砖引玉下。
第一种方法: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 = ;
public const int OF_SHARE_DENY_NONE = 0x40;
public readonly IntPtr HFILE_ERROR = new IntPtr(-);
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("没有被占用!");
}
第二种方法: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;//true表示正在使用,false没有使用
}
项目代码的部分(VB.Net)
Sub Prepare()
If File.Exists(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, )
Threading.Thread.Sleep()
While (IsFileInUse("LimitA.log"))
Threading.Thread.Sleep()
End While If File.Exists(logRW) Then
Dim All As String = My.Computer.FileSystem.ReadAllText(logRW)
'检查LogRW的0x01的位置的值是否为0x08
If All.Contains("Read EC Byte 0x01 = 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)())
Console.WriteLine("Limit Current: " & LimitA)
LogStr = LogStr & vbCrLf & "Limit Current: " & LimitA
Exit Do
End If
Loop
End Using Catch ex As Exception
Console.WriteLine(ex.Message & Err.Description)
Environment.Exit()
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, FileMode.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