如何检查驱动器是否已在 C# 中使用 net use 成功映射?

How can I check if a drive was successfully mapped with net use in C#?

我尝试在执行 net use 命令后测试该目录是否存在,但是在 mapDrive() 完成驱动器映射之前正在执行 checkMappedDrive()。

public void mapDrive(String driveChar, String server, String user, String password){
    String path = "use "+driveChar+": "+server +" /user:"+user+ " "+password;
    proc.StartInfo.FileName = "net";
    proc.StartInfo.Arguments = path;
    proc.StartInfo.UseShellExecute = false;
    proc.Start();

   if(checkMappedDrive(driveChar)){
      //nice
   }else{
      //error
   }

}

public bool checkMappedDrive(String driveChar){

   String drive = Path.GetPathRoot(driveChar.ToUpper()+":\"); 
   Debug.WriteLine("Checking: " + drive);
    if (!Directory.Exists(drive)){
            proc.Kill();
            //bad
    return false;
    }
      //nice
    return true;
}

您可以使用 Process.WaitforExit:

public void mapDrive(String driveChar, String server, String user, String password){
    String path = "use "+driveChar+": "+server +" /user:"+user+ " "+password;
    proc.StartInfo.FileName = "net";
    proc.StartInfo.Arguments = path;
    proc.StartInfo.UseShellExecute = false;
    proc.Start(); 
    proc.WaitForExit(10000); // wait 10 seconds at a maximum

   if(checkMappedDrive(driveChar)){
      //nice
   }else{
      //error
   }

}

使用proc.WaitForExit();等待进程完成

MSDN: Process.WaitForExit Method