- Home /
Mac/PC differences in directory symbols '\' and '/'
Hi,
Some C# code from a PC project was broken on a Mac because of the directory path formatting as;
Assets\myFolder\myThing
Changing it to the following fixes it for the Mac
Assets/myFolder/myThing
What's the best way to handle this situation to ensure the code runs cross-platform?
$$anonymous$$ost Unity APIs that deal with paths should handle this properly. How is it exactly broken?
public class PresetLoader : $$anonymous$$onoBehaviour {
string dataFolder = @"Assets\";
Dictionary<string, CustomPrefab> prefabs = new Dictionary<string, CustomPrefab>();
void Start () {
foreach(string dataFile in Directory.GetFiles(dataFolder, "*.data", SearchOption.AllDirectories)) {
string[] lines = File.ReadAllLines(dataFile);
string name = dataFile.Substring(dataFile.LastIndexOf("\\")+1, dataFile.LastIndexOf(".") - (dataFile.LastIndexOf("\\")+1));
prefabs.Add(name, new CustomPrefab(name, lines));
}
}
}
First of all it can't find "Assets\": DirectoryNotFoundException: Directory 'Assets\' not found.
If I fix that, then it parses the Substring incorrectly as: "Assets/Chapter 3/BasicSystem/EntityDataFiles/$$anonymous$$yFile"
I'm trying to extract just the file name from that full path.
Changing / to \ For example
Substring(dataFile.LastIndexOf("\\")
Substring(dataFile.LastIndexOf("/")
results in the correct result of '$$anonymous$$yFile'
Answer by HarshadK · Sep 17, 2014 at 08:37 AM
Actually On Mac and Windows the path separator is "\" and for Linux it is "/".
One way to overcome this issues is to use Path.DirectorySeparatorChar for avoiding such issues.
Thanks for both solutions. I'll use Path.DirectorySeparatorChar for now as it's ready to go. Shame they used such a long name, you end up with strings a mile long ;)
Answer by Baste · Sep 17, 2014 at 08:33 AM
Wrap the delimiter symbol in a property, and use the #if conditional to make it return '\' on windows platforms (the only platform to use \ as a delimiter). Something like this:
public static string delim {
get {
string delimString = "/";
#if (UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN)
delimString = "\\";
#endif
return delimString;
}
}
Note that '\' must be escaped by another '\'.