using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
namespace PModifyFileNameT
{
/// <summary>
/// 判断文件是否存在及是否打开
/// </summary>
public class FileState
{
public FileState()
{
}
[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 static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
/// <summary>
/// 文件是否处于打开状态
/// </summary>
/// <param name="strFileName">文件名称</param>
/// <returns>是否打开</returns>
public static bool GetFileState(string strFileName)
{
bool blnIsOpen = false;
IntPtr vHandle = _lopen(strFileName, OF_READWRITE | OF_SHARE_DENY_NONE);
if (vHandle == HFILE_ERROR)
{
// 文件处于打开状态
return true;
}
CloseHandle(vHandle);
return blnIsOpen;
}
/// <summary>
/// 文件是否已存在
/// </summary>
/// <param name="strFileName">文件名</param>
/// <returns>是否存在</returns>
public static bool GetFileExists(string strFileName)
{
bool blnIsExists = false;
if (File.Exists(strFileName))
{
return true;
}
return blnIsExists;
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
namespace PModifyFileNameT
{
/// <summary>
/// 判断文件是否存在及是否打开
/// </summary>
public class FileState
{
public FileState()
{
}
[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 static readonly IntPtr HFILE_ERROR = new IntPtr(-1);
/// <summary>
/// 文件是否处于打开状态
/// </summary>
/// <param name="strFileName">文件名称</param>
/// <returns>是否打开</returns>
public static bool GetFileState(string strFileName)
{
bool blnIsOpen = false;
IntPtr vHandle = _lopen(strFileName, OF_READWRITE | OF_SHARE_DENY_NONE);
if (vHandle == HFILE_ERROR)
{
// 文件处于打开状态
return true;
}
CloseHandle(vHandle);
return blnIsOpen;
}
/// <summary>
/// 文件是否已存在
/// </summary>
/// <param name="strFileName">文件名</param>
/// <returns>是否存在</returns>
public static bool GetFileExists(string strFileName)
{
bool blnIsExists = false;
if (File.Exists(strFileName))
{
return true;
}
return blnIsExists;
}
}
}
本文介绍了一个.NET程序中用于检查文件是否已被打开或存在的实用方法。通过使用PInvoke调用Windows API,此方法能够有效地帮助开发者判断文件的状态,这对于避免文件操作冲突十分关键。

被折叠的 条评论
为什么被折叠?



