DotNetCore: cross platform version of GetInvalidFileNameChars?

Viewed 864

I'm building a .Net Core 2.0 console application that will run on both Windows and Ubuntu systems. I have a string that needs to be converted into a safe file name. Currently I'm using the following code to achieve this:

var safeName = string.Join("-", name.Split(Path.GetInvalidFileNameChars()));

It works, but it will produce different results on different operating system as Linux allows characters that Windows will not allow. I like a solution that produces the same result on all of the systems.

Is there a cross platform version of GetInvalidFileNameChars that will return characters for all platforms?

2 Answers

I don't think there is a "cross-platform" version in the BCL, but you can easily make one yourself by copying the Windows version of GetInvalidFileNameChars, because the Unix version is just a subset of these and they're not likely to change often:

        public static char[] GetInvalidFileNameChars() => new char[]
        {
            '\"', '<', '>', '|', '\0',
            (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
            (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
            (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
            (char)31, ':', '*', '?', '\\', '/'
        };

Looks like the following will will work:

var invalidCharStr =

    //printable chars linux/unix
    "/" +

    //unprintable chars linux/unix
    Convert.ToChar(0) +

    //printable chars Windows
    @"><:""/\|?*" +

    //unprintable chars Windows: 0-31
    new string(Enumerable.Range(0, 32).Select(Convert.ToChar).ToArray());

Have them as an array like:

var invalidChars = invalidCharStr.ToArray();
Related