简体   繁体   中英

C# Directory.GetCurrentDirectory and drives other than C:

For some reason when my program is installed on a drive other than C:\\ the code below (c# .net 2.0) is unable to find and run the program2.exe. Am I doing something wrong here?

try
{
    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.StartInfo.FileName = Directory.GetCurrentDirectory() +
                              "\\Folder\\program2.exe";
    proc.Start();
}
catch
{
    MessageBox.Show("Unable to locate program");
}

Could it be because your program is in the root folder of another drive, eg R:\\ , rather than a subdirectory, eg R:\\Program ?

For reasons such as this, it is considered bad practice in C# to concatenate paths using the literal backslash character. Instead, you should use Path.Combine :

proc.StartInfo.FileName = Path.Combine(
    Directory.GetCurrentDirectory(),
    "Folder",
    "program2.exe"
);

Furthermore, it may be that Directory.GetCurrentDirectory() does not point to the directory you think it does. In general, this could return any directory on your system, and is unrelated to where your program resides or was launched from. Therefore, I recommend to use one of these instead:

  • If you are using WinForms, Application.ExecutablePath
  • Otherwise, Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM