2

In my application i have some files in remote location say \\server\sharedfolder, program does operations like MOVE or DELETE based on user operation and respective files are moved to another user or folder. But if a folder or file is opened by some user the operation fails obviously.

My goal is to log the user that is currently holding the file including process, machine name and username.

solutions tried:

How do I determine the owner of a process in C#?

How do I find out which process is locking a file using .NET?

Also tried impersonation with above solutions but it did not work.

on server i checked in computer management-> system tools-> opened files has all the log of the users and other details.

My solution is completely programmatic using c#.

P.S cannot share any code or snippet because of policies.

UPDATE:

for any one looking for similar approach or solutions, accepted answer along with this one here and impersonation with admin privileges combined, will result in the final output.

Zameer Fouzan
  • 666
  • 6
  • 15
  • Does the same application lock the files with other user, or any other application lock them ? – Mutlu Kaya Dec 13 '17 at 08:46
  • other application, basically files are either text files or office files. – Zameer Fouzan Dec 13 '17 at 09:12
  • I guess this might help https://stackoverflow.com/questions/581219/find-out-who-is-locking-a-file-on-a-network-share – Mutlu Kaya Dec 13 '17 at 09:47
  • I did mention this in my question that i found this out, i am in need of solution which is done using c# – Zameer Fouzan Dec 13 '17 at 10:41
  • sorry if I misundestood you. I mean that there are several tools in the link like OpenFiles or PsFile and they can be executed on command promt in the remote machine, so you can execute one of the tools by opening new cmd in your application and you can read the result. Again, I' m not sure it will solve your problem, it's just an idea. – Mutlu Kaya Dec 13 '17 at 10:56
  • 2
    Probably this project can help you? https://github.com/michaelknigge/forcedel , In specific look at this https://github.com/michaelknigge/forcedel/blob/6d20f70510a29c02145e50ca9a6f46e76025cc1d/src/UsedFileDetector.cs#L30 – Tarun Lalwani Dec 16 '17 at 16:42
  • @ZameerFouzan, any update on the links i posted? – Tarun Lalwani Dec 22 '17 at 13:16
  • @TarunLalwani thank you for the links, i tried using it, but i had to redo alot of things to use this in my application. instead i got a solution from Hirad's ans below. sorry. totally got occupied with pre christmas schedule at job. – Zameer Fouzan Dec 24 '17 at 18:28

1 Answers1

1

There is another answer to this here at: stackoverflow.com/questions/317071/...

I have tried multiple solutions for this but the only one that I got the proper answer was the one Eric J. has responded. I tested this one and it works properly for the files with normal size and also I didn't get any proper answer for the process that is locked by windows services (Like MSSQL Service). This is done by win32 api.

I just reiterate the answer from Eric J.:

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;
    }
}
Hirad Nikoo
  • 1,599
  • 16
  • 26
  • Hey @Hirad Nikoo, thanks for this. this did not entirely solve my problem, but it returns the process that is holding the file, and used it and did some work around and combined with previously tried solution and made it work for my purpose and it returns the username along with its domain. Apologies that bounty got expired as i got occupied with hectic schedule of regular job. – Zameer Fouzan Dec 24 '17 at 18:31
  • @ZameerFouzan No worries I'm just glad it worked for you. I'm not here for the points and also the answer wasn't really mine to begin with. :) – Hirad Nikoo Dec 26 '17 at 06:14