C# 判断文件是否被占用
Posted LuoCore
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 判断文件是否被占用相关的知识,希望对你有一定的参考价值。
/// <summary>
/// 文件是否被占用
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
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 (Exception ex)
{
Console.WriteLine(ex);
inUse = false;
}
finally
{
if (fs != null)
fs.Close();
}
return inUse;//true表示正在使用,false没有使用
}
这个能解除占用问题
private const int OF_READWRITE = 2;
private const int OF_SHARE_DENY_NONE = 0x40;
private static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
/// <summary>
/// 关闭文件句柄
/// </summary>
/// <param name="hObject"></param>
/// <returns></returns>
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
/// <summary>
/// 判断文件是否打开
/// </summary>
/// <param name="lpPathName">文件名称</param>
/// <param name="iReadWrite"></param>
/// <returns></returns>
[DllImport("kernel32.dll")]
private static extern IntPtr _lopen(string lpPathName, int iReadWrite);
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
{
IntPtr vHandle = _lopen(fileName, OF_READWRITE | OF_SHARE_DENY_NONE);
CloseHandle(vHandle);
}
finally
{
if (fs != null)
fs.Close();
}
return inUse;//true表示正在使用,false没有使用
}
以上是关于C# 判断文件是否被占用的主要内容,如果未能解决你的问题,请参考以下文章