0

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;
}
tec
  • 999
  • 3
  • 18
  • 40
  • Use Process.WaitForExit() to make sure your shell operation completes. And then check your Process's ExitCode for any errors. You may still need to check your folder has been mapped successfully after that. – Murray Foxcroft Nov 28 '16 at 08:33
  • I wanted to finish the process because when the user is not valid, it took around 10-15 sec to finish the process, maybe it's the server overloading or something. – tec Nov 28 '16 at 08:46

2 Answers2

2

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
   }

}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Don't forget to use the one with a timeout as parameter: https://msdn.microsoft.com/en-us/library/ty0d8k56.aspx – RvdK Nov 28 '16 at 08:31
  • So, the only way is to wait a few seconds right?When I put an invalid user it took 20 sec :/ – tec Nov 28 '16 at 08:47
  • @tomyforever: the method doesn't wait x-seconds, it'll wait until the process exists, but if the wait-time exceeds x-milliseconds(10 seconds above) it will continue. So the parameter to `Process.WaitForExit` should be twice as much as it normally needs to map the drive. – Tim Schmelter Nov 28 '16 at 09:13
  • @TimSchmelter Thanks for clarify. – tec Nov 28 '16 at 09:15
0

Use proc.WaitForExit(); in order to wait till the process finished

MSDN: Process.WaitForExit Method

dknaack
  • 60,192
  • 27
  • 155
  • 202