[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:\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;

}

项目代码的部分(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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值