Insert my own illegal characters in Path.GetInvalidFileNameChars () in C #

How can I expand Path.GetInvalidFileNameCharsto include my own character set, which is illegal in my application?

string invalid = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());

If I wanted to add '&' as an illegal character, can I do this?

+3
source share
4 answers

You cannot modify an existing function, but you can write a wrapper function that returns Path.GetInvalidFileNameChars()your illegal characters.

public static string GetInvalidFileNameChars() {
    return Path.GetInvalidFileNameChars().Concat(MY_INVALID_FILENAME_CHARS);
}
+2
source
typeof(Path).GetField("InvalidFileNameChars", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, new[] { 'o', 'v', 'e', 'r', '9', '0', '0', '0' });
+15
source

:

var invalid = Path.GetInvalidFileNameChars().Concat(new [] { '&' });

IEnumerable<char> , .

:

using System.IO;
using System.Linq;

class Program
{
    static void Main()
    {
        // This is the sequence of characters
        var invalid = Path.GetInvalidFileNameChars().Concat(new[] { '&' });
        // If you want them as an array you can do this
        var invalid2 = invalid.ToArray();
        // If you want them as a string you can do this
        var invalid3 = new string(invalid.ToArray());
    }
}
+3

.

public static class Extensions
{
    public static char[] GetApplicationInvalidChars(this char[] input)
    {
        //Your list of invalid characters goes below.
        var invalidChars = new [] { '%', '#', 't' };
        return String.Concat(input, invalidChars).ToCharArray();
    }
}

:

string invalid = Path.GetInvalidFileNameChars().GetApplicationInvalidChars();

, .

+1

Source: https://habr.com/ru/post/1782779/


All Articles