Use relative Path in Microsoft Surface application?
I convert my wave file into a mp3 file by the following code:
internal bool convertToMp3()
{
string lameEXE = @"C:\Users\Roflcoptr\Documents\Visual Studio 2008\Projects\Prototype_Concept_2\Prototype_Concept_2\lame\lame.exe";
string lameArgs = "-V2";
string wavFile = fileName;
string mp3File = fileName.Replace("wav", "mp3");
Process process = new Process();
pr开发者_StackOverflow中文版ocess.StartInfo = new ProcessStartInfo();
process.StartInfo.FileName = lameEXE;
process.StartInfo.Arguments = string.Format("{0} {1} {2}", lameArgs, wavFile, mp3File);
process.Start();
process.WaitForExit();
int exitCode = process.ExitCode;
if (exitCode == 0)
{
return true;
}
else
{
return false;
}
}
This works, but now I'd like to not use the absolut path to the lame.exe but a relative path. I included a lame.exe in the folder /lame/ on the root of the project. How can I reference it?
If you have rights to distribute the file with your application, then one way of doing it would be to include the .exe file as an item in your C# project, with
Build Action = None
Copy to Output Directory = Copy if newer
You can then just use
string lameEXE = @"lame.exe"
Assuming your binary app is in Debug folder and the lame folder is in the main project directory:
string lameEXE = @"..\..\lame\lame.exe
Hovewer, folders structure will be probably different in your release version.
Directly using a path relative to the application directory is a bad idea since the working directory might not be identical to the application directory. This can lead to bugs and security holes. For example you might execute files in untrusted directories.
Some cases where the working directory isn't identical to the application directory:
- The user opens a file from the explorer. Then the working directory is the directory where the file is in
- Depending on the settings Common Dialogs(OpenFileDialog, SaveFileDialog) change the working directory.
So you should expand it relative to the project directory. Unfortunately I know of no clean library function which does that for you. In simple cases this can be done by concatenating the relative path to the application directory:
string appDir = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]) + "\\";
const string relativePath=@"..\..\lame.exe";//Whatever relative path you want
string absolutePath=appDir+relativePath;
...
process.StartInfo.FileName =absolutePath;
...
精彩评论