Directory.GetFiles with '/' on any platform

580 Views Asked by At

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.

2

There are 2 best solutions below

1
AKX On BEST ANSWER

Unfortunately that doesn't seem to be possible.

Path.DirectorySeparatorChar and Path.AltDirectorySeparatorChar depend on the OS your app is running on, and are read-only.

According to the docs DirectorySeparatorChar is \ on Windows and / everywhere else, and Path.AltDirectorySeparatorChar is (currently) always /.

1
Joshua 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, '/'));