Reputation: 3409
I realized that my code has a lot of paths of the form C:\folder\pathtofile, and I was wondering what is typically done to allow code to be usable under different file systems?
I was hoping there was some environment property I could check in C# that would give me either forward slash or backslash in order to create new path strings.
Upvotes: 0
Views: 1067
Reputation: 127543
Use the commands Path.Combine
to combine strings together using the path separator or if you need more manual control Path.DirectorySeparatorChar
will give you the platform specific character.
public static string GetConfigFilePath()
{
//Returns "C:\Users\{Username}\AppData\Roaming"
// or "C:/Users/{Username}/AppData/Roaming" depending on CLR running.
var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
//Returns "C:\Users\{Username}\AppData\Roaming\MyProgramName\MyConfigFile.xml"
// or "C:/Users/{Username}/AppData/Roaming/MyProgramName/MyConfigFile.xml" depending on CLR running.
var configPath = Path.Combine(appData, "MyProgramName", "MyConfigFile.xml");
return configPath;
}
Upvotes: 1