windows 重新连接断开的网络驱动器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1808226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 13:30:02  来源:igfitidea点击:

Reconnecting a disconnected network drive

c#.netwindows

提问by Kjensen

If I try to write a file to a network drive, that is disconnected, I get an error.

如果我尝试将文件写入已断开连接的网络驱动器,则会出现错误。

If I doubleclick the drive in explorer, the network drive is reconnected.

如果我在资源管理器中双击驱动器,网络驱动器将重新连接。

Using System.Io.Driveinfo.IsReady I can check if a drive is ready - but how can I reconnect it in code?

使用 System.Io.Driveinfo.IsReady 我可以检查驱动器是否准备就绪 - 但是如何在代码中重新连接它?

采纳答案by t0mm13b

Would this codewhich shows how to map the drive and unmap it dynamically at runtime do? This is on CodeGuru.

这段显示如何在运行时动态映射驱动器和取消映射的代码可以吗?这是在 CodeGuru 上。

回答by casiosmu

As @AndresRohrAtlasInformatik pointed out, the accepted solution doesn't work with Windows Vista and later.

正如@AndresRohrAtlasInformatik 指出的那样,已接受的解决方案不适用于 Windows Vista 及更高版本。

So my solution is to 'simply' start explorer as hidden window, go to the network drive and close explorer. The latter is a bit more difficult (see here) because explorer has very special behaviour for multiple windows.

所以我的解决方案是“简单地”将资源管理器作为隐藏窗口启动,转到网络驱动器并关闭资源管理器。后者有点困难(请参阅此处),因为资源管理器对多个窗口具有非常特殊的行为。

ProcessStartInfo info = new ProcessStartInfo("explorer.exe", myDriveLetter);
info.WindowStyle = ProcessWindowStyle.Hidden;
Process process = new Process();
process.StartInfo = info;
process.Start();
Thread.Sleep(1000);
//bool res = process.CloseMainWindow(); // doesn't work for explorer !!
//process.Close();
//process.WaitForExit(5000);

// https://stackoverflow.com/a/47574704/2925238
ShellWindows _shellWindows = new SHDocVw.ShellWindows();
string processType;

foreach (InternetExplorer ie in _shellWindows)
{
    //this parses the name of the process
    processType = System.IO.Path.GetFileNameWithoutExtension(ie.FullName).ToLower();

    //this could also be used for IE windows with processType of "iexplore"
    if (processType.Equals("explorer") && ie.LocationURL.Contains(myDriveLetter))
    {
        ie.Quit();
    }
}