Relative path in .NET
I am running my C# application from "D:\App\program.cs". My application needs to execu开发者_如何转开发te a file placed in "C:\Program Files\software\abc.exe".
How can I set the relative path in my program to execute the "abc.exe"?
To answer the question how to get a path that shows the relative location of pathB from pathA. You can use the Uri class to get the relative path.
string pathA = @"C:\App\program.cs";
string pathB = @"C:\program files\software\abc.exe";
System.Uri uriA = new Uri(pathA);
System.Uri uriB = new Uri(pathB);
Uri relativeUri = uriA.MakeRelativeUri(uriB);
string relativeToA = relativeUri.ToString();
Console.WriteLine(relativeToA);
This yields "../program%20files/software/abc.exe" for the relative path.
I have changed your example from D to C though because you can't have a relative path for two locations on different drive letters, although the above code still works, just yields the absolute.
OR if the c# bit is a red herring, and as I now understand you want to run a batch file:
in batch file put:
cd c:\program files\software\
abc.exe
abc.exe will then execute from software folder and not folder of the batch file.
You shouldn't be using relative path for referring something from Program Files. I would recommend to use Environment.GetFolderPath (and Environment.SpecialFolder) to get path to Program Files and then use some config setting to get reminder path to the program.
It's not clear what you mean by "set relative path", but if you're using Process
and ProcessStartInfo
to run the executable, I would suggest that you use an absolute path to specify the executable, and ProcessStartInfo.WorkingDirectory
to tell the process where to run (so that relative paths will be evaluated appropriately within the new process).
EDIT: If you want the batch file to run c:\Program Files\Software\abc.exe then the contents of the batch file should be just:
"c:\Program Files\Software\abc.exe"
(Note the quotes to allow for space.)
I don't see what this has got to do with relative pathnames though.
If the application is in Program Files
then you can create a batch file like
"%ProgramFiles%\software\abc.exe"
精彩评论