简体   繁体   中英

C#: Path.Combine not giving full path

Below code not giving full path, what could be the reason?

var X = Path.Combine( Environment.GetEnvironmentVariable("PROGRAMFILES(X86)"), "/ABC/XYZ.exe");

Output : /ABC/XYZ.exe

Expected : C:/Program Files (x86)/ABC/XYZ.exe

The second argument to Path.Combine ("/ABC/XYZ.exe") starts with a slash, which is putting you back at the root. Remove this leading slash and you should get the output you are after.

Path.Combine(Environment.GetEnvironmentVariable("PROGRAMFILES(X86)"), "ABC/XYZ.exe")

From the documentation :

If path2 does not include a root (for example, if path2 does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If path2 includes a root, path2 is returned.

Use the following code instead:

var programFilesPath = System.Environment.GetFolderPath(
    System.Environment.SpecialFolder.ProgramFiles);
var X = Path.Combine( programFilesPath, "ABC/XYZ.exe" );

Notice I removed the leading '/' character. When it is present, the Path.Combine will use the second path instead of combination as it takes it as root. System.Environment.SpecialFolder.ProgramFiles always refers to the ProgramFiles (x86) version of Program Files.

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