Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force Windows to reconnect to network drive

We try to access a directory which is within a network directory but get wrong results (C#/Windows):

var exists = Directory.Exists("Z:\\Sessions\\Data1");

"Z" is the network directory, "Sessions" is a directory where a recording software constantly creates directories (e.g. "Data1") and puts some data in it. It seems that Windows caches the wrong state about Data1: The method returns false. But when I access the directory via Explorer it's here. When I run the method (Directory.Exists) after accessing the directory with Explorer, it returns true. Of course I can guarantee that the directory actually exists at the first attempt.

What is the reason for this behaviour? What can I do about it?

Edit: It seems that windows could not connect the network drive to the remote computer. When I try to navigate into the directory with Explorer it automatically tries to connect the drive.

So the question changes: Is there a way to force windows to try a reconnect via .NET?

Solution: Reconnecting a disconnected network drive

like image 281
nepa Avatar asked Dec 25 '11 13:12

nepa


People also ask

Why do mapped drives not reconnect?

If the device has not established a network connection by the time of logon, the startup script won't automatically reconnect network drives. A log file (StartupLog. txt) will be created in the %TEMP%\ folder. Log off, and then log back on to the device to open the mapped drives.

How do I get my network drive back online?

From the file explorer ribbon, under the 'Easy Access' drop down menu, you could toggle from "offline" to "online". In doing so, you would switch the mapped drive status to "online" and access to the entirety of drive's content would then be possible/granted.

Why is my network drive disconnected?

This behavior occurs because the systems can drop idle connections after a specified time-out period (by default, 15 minutes) to prevent wasting server resources on unused sessions. The connection can be re-established quickly, if necessary.


2 Answers

I'm not sure which version of mpr.dll the solution link above works with, but I am using Win7 and have a slightly different version (although similar). This entry point is:

    [DllImport("mpr.dll", SetLastError = true, EntryPoint = "WNetRestoreSingleConnectionW", CharSet = CharSet.Unicode)]
    internal static extern int WNetRestoreSingleConnection( IntPtr windowHandle,
                                                            [MarshalAs(UnmanagedType.LPWStr)] string localDrive,
                                                            [MarshalAs(UnmanagedType.Bool)] bool useUI);

then:

IntPtr hWnd = new IntPtr(0);
int res = WNetRestoreSingleConnection(hWnd, <your drive path>, false);

You'll have to add your own error checking / handling.

like image 145
Jess Avatar answered Sep 22 '22 16:09

Jess


I too use a remote drive and it takes a few seconds to connect, so I just wait and works every time. If it does not connect, it will send an email and I will check it.

        logger.Info("Create Z: drive ");
        System.Diagnostics.Process process = new System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = @"/C net use z: \\" + Tools.servername + @"\SHARE_NAME_HERE /user:USER_NAME_HERE PASSWORD_HERE";
        process.StartInfo = startInfo;
        process.Start();
        logger.Info("Z: drive created ");

        // wait get Z:
        int xtimestimeout = 5;
        while (!Directory.Exists(@"Z:\") & (xtimestimeout > 0))
        {
            Application.DoEvents();
            SetBalloonTip(@"Program", @"connecting... please wait");
            ShowBalloon();
            logger.Info("Creating Z:... waiting...");
            Application.DoEvents();
            System.Threading.Thread.Sleep(3000);
            xtimestimeout -= 1;
        }

        // check for sucessfull creation of Z: in server Z:\somedirectory
        if (!Directory.Exists(@"Z:\"))
        {
            SendEmail2("Oh my... help!", "drive Z: not created <<< CHECK!");
            logger.Info("Z: email sent because of not created");
        }
        logger.Info("Z: drive created successfully.");
like image 39
Roger Deep Avatar answered Sep 21 '22 16:09

Roger Deep