编辑:显然没有简单或方便的方法来了解文件是否打开/被进程持有。我认为这是 Windows 操作系统本身的问题或设计决定,因为即使像 Process Explorer 这样的程序也无法判断我何时在记事本中打开了“mytext.txt”文件,除了它的窗口:)进一步的研究也显示了获得的唯一方法这些信息可靠地深入到系统驱动程序中。我的问题仍然存在,如果有人能告诉我这个驱动程序解决方案的路径,我也很感激。
p.s:我真诚地认为应该是这个答案的简单解决方案。我的意思是,感觉它是整个操作系统中缺少的功能 - 无法判断文件是否打开?真的吗?甚至没有 API 方法?这对我来说不合适。
-- 原始问题 --
我一直在网上搜索以找到这个问题的答案。显然在 Windows Vista 之后添加了一个名为 Restart Manager 的功能,我们可以调用该 dll 的方法来检查文件是否被锁定。
但是,当我在一个简单的控制台应用程序中尝试此操作时(受这篇文章的启发:https://blogs.msdn.microsoft.com/oldnewthing/20120217-00/?p=8283 和这个 SO 答案 https://stackoverflow.com/a/20623311/1858013)它可以判断 office 文件(xls、doc 等...)是否被锁定/打开但在记事本中打开 .txt 文件时不打开,或者在 Visual Studio 中打开项目时打开 .sln 文件时不打开。
我的程序正在监视用户系统中的预设文件夹(例如,Documents 文件夹),我想在该文件夹中打开任何文件 时触发一个事件。程序本身不会修改文件或使用该文件,因此锁定或解锁不是问题,我只是想在受监视文件夹中的任何程序中打开文件时收到通知。
现在,我正在使用这段代码来查找哪些进程正在锁定文件,但我觉得有一种比使用 Win32 api 更容易知道文件何时打开的方法。
static public class FileUtil
{
[StructLayout(LayoutKind.Sequential)]
struct RM_UNIQUE_PROCESS
{
public int dwProcessId;
public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
}
const int RmRebootReasonNone = 0;
const int CCH_RM_MAX_APP_NAME = 255;
const int CCH_RM_MAX_SVC_NAME = 63;
enum RM_APP_TYPE
{
RmUnknownApp = 0,
RmMainWindow = 1,
RmOtherWindow = 2,
RmService = 3,
RmExplorer = 4,
RmConsole = 5,
RmCritical = 1000
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
struct RM_PROCESS_INFO
{
public RM_UNIQUE_PROCESS Process;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
public string strAppName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
public string strServiceShortName;
public RM_APP_TYPE ApplicationType;
public uint AppStatus;
public uint TSSessionId;
[MarshalAs(UnmanagedType.Bool)]
public bool bRestartable;
}
[DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
static extern int RmRegisterResources(uint pSessionHandle,
UInt32 nFiles,
string[] rgsFilenames,
UInt32 nApplications,
[In] RM_UNIQUE_PROCESS[] rgApplications,
UInt32 nServices,
string[] rgsServiceNames);
[DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);
[DllImport("rstrtmgr.dll")]
static extern int RmEndSession(uint pSessionHandle);
[DllImport("rstrtmgr.dll")]
static extern int RmGetList(uint dwSessionHandle,
out uint pnProcInfoNeeded,
ref uint pnProcInfo,
[In, Out] RM_PROCESS_INFO[] rgAffectedApps,
ref uint lpdwRebootReasons);
/// <summary>
/// Find out what process(es) have a lock on the specified file.
/// </summary>
/// <param name="path">Path of the file.</param>
/// <returns>Processes locking the file</returns>
/// <remarks>See also:
/// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
/// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
///
/// </remarks>
static public List<Process> WhoIsLocking(string path)
{
uint handle;
string key = Guid.NewGuid().ToString();
List<Process> processes = new List<Process>();
int res = RmStartSession(out handle, 0, key);
if (res != 0) throw new Exception("Could not begin restart session. Unable to determine file locker.");
try
{
const int ERROR_MORE_DATA = 234;
uint pnProcInfoNeeded = 0,
pnProcInfo = 0,
lpdwRebootReasons = RmRebootReasonNone;
string[] resources = new string[] { path }; // Just checking on one resource.
res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);
if (res != 0) throw new Exception("Could not register resource.");
//Note: there's a race condition here -- the first call to RmGetList() returns
// the total number of process. However, when we call RmGetList() again to get
// the actual processes this number may have increased.
res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);
if (res == ERROR_MORE_DATA)
{
// Create an array to store the process results
RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
pnProcInfo = pnProcInfoNeeded;
// Get the list
res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
if (res == 0)
{
processes = new List<Process>((int)pnProcInfo);
// Enumerate all of the results and add them to the
// list to be returned
for (int i = 0; i < pnProcInfo; i++)
{
try
{
processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
}
// catch the error -- in case the process is no longer running
catch (ArgumentException) { }
}
}
else throw new Exception("Could not list processes locking resource.");
}
else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");
}
finally
{
RmEndSession(handle);
}
return processes;
}
}
如有任何帮助,我们将不胜感激。
最佳答案
您需要知道谁打开了文件,还是只需要知道文件是否已锁定。
如果您只需要知道它是否被锁定,您可以使用 FileSystemWatcher。该组件将监视某个文件夹的各种变化。
关于c# - 监视文件夹并查找文件是否在 Windows 应用程序中打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37276962/