简体   繁体   English

如何强制Windows重新连接到网络驱动器

[英]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): 我们尝试访问网络目录中的目录但得到错误的结果(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 (eg "Data1") and puts some data in it. “Z”是网络目录,“Sessions”是记录软件不断创建目录(例如“Data1”)并在其中放入一些数据的目录。 It seems that Windows caches the wrong state about Data1: The method returns false. 似乎Windows缓存了关于Data1的错误状态:该方法返回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. 在使用Explorer访问目录后运行方法(Directory.Exists)时,它返回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. 编辑:似乎Windows无法将网络驱动器连接到远程计算机。 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? 所以问题发生了变化: 是否有办法强制Windows尝试通过.NET重新连接?

Solution: Reconnecting a disconnected network drive 解决方案: 重新连接断开的网络驱动器

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). 我不确定上面的解决方案链接使用哪个版本的mpr.dll,但我使用的是Win7并且版本略有不同(尽管类似)。 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. 您必须添加自己的错误检查/处理。

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.");

What is the reason for this behaviour? 这种行为的原因是什么?

Quote from the documentation : 文档中引用:

If you do not have at a minimum read-only permission to the directory, the Exists method will return false. 如果您没有对目录的最低只读权限,则Exists方法将返回false。


What can I do about it? 我能做些什么呢?

Ensure that you are running your .NET application under an account that has at least read-only permission to access this folder. 确保您在至少具有访问此文件夹的只读权限的帐户下运行.NET应用程序。 Notice that if you are writing this in an ASP.NET application this probably won't be the case so depending on which account you configured your web server to execute your application under, take the necessary steps to grant permissions to this account. 请注意,如果您在ASP.NET应用程序中编写此文件,则可能不会出现这种情况,因此,根据您将Web服务器配置为执行应用程序的帐户,请采取必要步骤为此帐户授予权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用C#-Windows 8-10更改网络驱动器的名称? - How to change the name of a network drive with C# - Windows 8 - 10? 如何从 Windows 服务 map 网络驱动器 - How can I map a network drive from a Windows Service 如何从Windows服务映射网络驱动器? - How does one map network drive from windows service? 如何在网络断开后立即重新连接TcpClient - How to reconnect a TcpClient as soon as network unplugged and then plugged C#Windows在映射的网络驱动器上搜索 - C# windows search on mapped network drive 以编程方式将FTP和SFTP映射为Windows中的网络驱动器(网络重定向器) - Mapping FTP and SFTP as Network Drive in Windows programmatically (Network redirector) 如何在Windows Universal App中显示网络文件夹或本地驱动器中的图像 - How to display an image from a network folder or local drive in a Windows Universal App 如何从 Windows 服务访问连接到本地网络上路由器的 USB 驱动器 - How to access a USB drive attached to router on local network from windows service Windows UWP BluetoothLE设备重新连接 - Windows UWP BluetoothLEDevice reconnect 如果 Photon Network 突然断开连接或用户将网络从 wifi 切换到 Unity3d 中的数据,如何快速重新连接? - How to reconnect quickly if Photon Network disconnect suddenly or user switched network from wifi to data in Unity3d?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM