tomyforever tomyforever - 6 days ago 8
C# Question

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

I tried testing if the directory exists after executing the net use command, but checkMappedDrive() is executing before mapDrive() finish mapping the drive.

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;
}

Answer

You could use 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
   }

}
Comments