C# 记录进程ID、计算机名和文件所有者,该文件由windows server上使用c的另一个进程使用#

C# 记录进程ID、计算机名和文件所有者,该文件由windows server上使用c的另一个进程使用#,c#,.net,iis,windows-server,C#,.net,Iis,Windows Server,在我的应用程序中,我在远程位置有一些文件,例如\\server\sharedfolder,程序根据用户操作执行移动或删除等操作,并且相应的文件被移动到另一个用户或文件夹。但是,如果某个用户打开了某个文件夹或文件,操作显然会失败 我的目标是记录当前持有该文件的用户,包括进程、机器名和用户名 尝试过的解决方案: 还尝试使用上述解决方案模拟,但不起作用 在我签入的服务器上,计算机管理->系统工具->打开的文件包含所有用户日志和其他详细信息 我的解决方案完全是使用c#编程的 由于策略原因,p.S无法

在我的应用程序中,我在远程位置有一些文件,例如
\\server\sharedfolder
,程序根据用户操作执行移动或删除等操作,并且相应的文件被移动到另一个用户或文件夹。但是,如果某个用户打开了某个文件夹或文件,操作显然会失败

我的目标是记录当前持有该文件的用户,包括进程、机器名和用户名

尝试过的解决方案:

还尝试使用上述解决方案模拟,但不起作用

在我签入的服务器上,
计算机管理->系统工具->打开的文件
包含所有用户日志和其他详细信息

我的解决方案完全是使用c#编程的

由于策略原因,p.S无法共享任何代码或代码片段

更新:


对于任何寻求类似方法或解决方案的人,接受的答案以及与管理员权限相结合的模拟将导致最终输出

这里有另一个答案:

我为此尝试了多种解决方案,但我得到的唯一正确答案是有人作出了回应。我测试了这一个,它适用于正常大小的文件,而且对于被windows服务(如MSSQL服务)锁定的进程,我没有得到任何正确的答案。这是通过win32 api完成的

我只是重申以下几点:

使用System.Runtime.InteropServices;
使用系统诊断;
静态公共类FileUtil
{
[StructLayout(LayoutKind.Sequential)]
结构RM\u唯一\u进程
{
公共int-dwProcessId;
public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
}
常数int rmrebootreasonone=0;
const int CCH\u RM\u MAX\u APP\u NAME=255;
const int CCH\U RM\U MAX\U SVC\U NAME=63;
枚举RM_应用程序_类型
{
RmUnknownApp=0,
RmMainWindow=1,
RmOtherWindow=2,
RmService=3,
RmExplorer=4,
RmConsole=5,
RmCritical=1000
}
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)]
结构RM\u流程\u信息
{
公共RM_唯一的流程;
[Marshallas(UnmanagedType.ByValTStr,SizeConst=CCH\u RM\u MAX\u APP\u NAME+1)]
公共字符串名称;
[Marshallas(UnmanagedType.ByValTStr,SizeConst=CCH\u RM\u MAX\u SVC\u NAME+1)]
公共字符串strServiceShortName;
公共RM_应用程序类型应用程序类型;
公共应用状态;
公共uint TSSessionId;
[Marshallas(UnmanagedType.Bool)]
公共布尔布尔表;
}
[DllImport(“rstrtmgr.dll”,CharSet=CharSet.Unicode)]
静态外部内部RmRegisterResources(uint pSessionHandle,
UInt32文件,
字符串[]rgsFilenames,
UInt32应用程序,
[在]RM_唯一_流程[]RGA应用程序中,
UInt32 N服务,
字符串[]rgsServiceNames);
[DllImport(“rstrtmgr.dll”,CharSet=CharSet.Auto)]
静态外部int RmStartSession(out uint PSSessionHandle、int dwSessionFlags、字符串strSessionKey);
[DllImport(“rstrtmgr.dll”)]
静态外部内部RmEndSession(uint pSessionHandle);
[DllImport(“rstrtmgr.dll”)]
静态外部int RmGetList(uint dwSessionHandle,
需要的输出单元pnprocinfo,
参考uint pnProcInfo,
[In,Out]RM_流程_信息[]rgAffectedApps,
参考单元LPDWREBOTREASOS);
/// 
///找出在指定文件上有锁的进程。
/// 
///文件的路径。
///进程锁定文件
///另见:
/// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
/// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (观看时无代码版权)
/// 
/// 
静态公共列表WhoIsLocking(字符串路径)
{
uint手柄;
字符串键=Guid.NewGuid().ToString();
列表进程=新列表();
int res=RmStartSession(输出句柄,0,键);
如果(res!=0)抛出新异常(“无法开始重新启动会话。无法确定文件锁”);
尝试
{
const int ERROR\u MORE\u DATA=234;
uint pnProcInfoNeeded=0,
pnProcInfo=0,
lpdwRebootReasons=RmRebootReasonNone;
string[]resources=newstring[]{path};//只检查一个资源。
res=RmRegisterResources(handle,(uint)resources.Length,resources,0,null,0,null);
如果(res!=0)抛出新异常(“无法注册资源”);
//注意:这里有一个竞争条件——对RmGetList()的第一个调用返回
//进程总数。但是,当我们再次调用RmGetList()以获取
//这一数字的实际进程可能有所增加。
res=RmGetList(handle,out pnProcInfoNeeded,ref pnProcInfo,null,ref lpdwrebootoreasons);
如果(res==错误\u更多\u数据)
{
//创建一个数组来存储流程结果
RM_流程_信息[]流程信息=新的RM_流程_信息[PnProcInfoRequired];
pnProcInfo=pnProcInfoNeeded;
//获取列表
res=RmGetList(handle,out pnProcInfoNeeded,ref pnProcInfo,processInfo,ref lpdwrebootereasons);
如果(res==0)
{
进程=新列表((int)pnProcInfo);
//枚举所有结果并将它们添加到t
using System.Runtime.InteropServices;
using System.Diagnostics;
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;
    }
}