I'm trying to get a path with '/' char using Directory.GetFiles or Directory.GetDirectories whitout replacing the string each time I produce one. I would simply ask the librairie to use '/' as the directory separator even if I have some Macro telling him to use AltSeperator on specific OS.
Directory.GetFiles with '/' on any platform
580 Views Asked by Mathieu Van Nevel At
2
There are 2 best solutions below
1
On
General technique:
string MyPathCombine(string basename, string filename)
{
int idx = basename.Length;
if (idx == 0) return filename;
if (basename[idx - 1] == '/') --idx;
return filename;
}
IEnumerable<string> GetFilesSlash(string dirname)
=> Directory.GetFiles(dirname.Replace('/', Path.DirectorySeparatorCharacter)).Select((p) => MyPathCombine(dirname, Path.GetFileName(p));
If all your paths come from the real system, this simpler form would work, but if any come from another system, it will not as you could be poisoned by a \ character. Not that this is the only hazard however. It gets bumpy from here.
IEnumerable<string> GetFilesSlash(string dirname)
=> Directory.GetFiles(dirname.Replace('/', Path.DirectorySeparatorCharacter)).Select((p) => p.Replace(Path.DirectorySeparatorChar, '/'));
Unfortunately that doesn't seem to be possible.
Path.DirectorySeparatorCharandPath.AltDirectorySeparatorChardepend on the OS your app is running on, and are read-only.According to the docs
DirectorySeparatorCharis\on Windows and/everywhere else, andPath.AltDirectorySeparatorCharis (currently) always/.