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

时间:2011-12-25 13:18:47

标签: c# .net windows networking

我们尝试访问网络目录中的目录但得到错误的结果(C#/ Windows):

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

" Z"是网络目录,"会话"是一个记录软件不断创建目录(例如" Data1")并在其中放入一些数据的目录。 似乎Windows缓存了关于Data1的错误状态:该方法返回false。但是当我通过资源管理器访问目录时,它就在这里。在使用Explorer访问目录后运行方法(Directory.Exists)时,它返回true。当然,我可以保证第一次尝试时该目录实际存在。

这种行为的原因是什么?我该怎么办呢?

修改 似乎Windows无法将网络驱动器连接到远程计算机。当我尝试使用资源管理器导航到目录时,它会自动尝试连接驱动器。

所以问题改变了: 有没有办法强制Windows尝试通过.NET重新连接?

解决方案: Reconnecting a disconnected network drive

3 个答案:

答案 0 :(得分:4)

我不确定上面的解决方案链接使用哪个版本的mpr.dll,但我使用的是Win7并且版本略有不同(尽管类似)。这个切入点是:

    [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);

然后:

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

您必须添加自己的错误检查/处理。

答案 1 :(得分:2)

我也使用远程驱动器,连接需要几秒钟,所以我每次都在等待和工作。如果它没有连接,它将发送一封电子邮件,我会检查它。

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

答案 2 :(得分:0)

  

这种行为的原因是什么?

来自documentation

的引用
  

如果您没有对目录的最低只读权限,   Exists方法将返回false。


  

我该怎么办?

确保您在至少具有访问此文件夹的只读权限的帐户下运行.NET应用程序。请注意,如果您在ASP.NET应用程序中编写此文件,则可能不会出现这种情况,因此根据您将Web服务器配置为执行应用程序的帐户,请采取必要步骤为此帐户授予权限。