Inserting my own illegal characters into Path.GetInvalidFileNameChars() in C#
How can I extend the Path.GetInvalidFileNameChars
to include my own set of characters that is illegal in my application?
string invalid = new string(Path.GetInvalidFil开发者_JAVA技巧eNameChars()) + new string(Path.GetInvalidPathChars());
If I wanted to add the '&' as an illegal character, could I do that?
typeof(Path).GetField("InvalidFileNameChars", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, new[] { 'o', 'v', 'e', 'r', '9', '0', '0', '0' });
Try this:
var invalid = Path.GetInvalidFileNameChars().Concat(new [] { '&' });
This will yeild an IEnumerable<char>
with all invalid characters, including yours.
Here is a full example:
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());
}
}
You can't modify an existing function, but you can write a wrapper function that returns Path.GetInvalidFileNameChars()
and your illegal characters.
public static string GetInvalidFileNameChars() {
return Path.GetInvalidFileNameChars().Concat(MY_INVALID_FILENAME_CHARS);
}
An extension method is your best bet here.
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();
}
}
Then use it as follows:
string invalid = Path.GetInvalidFileNameChars().GetApplicationInvalidChars();
It will concatenate your invalid characters to what's already in there.
First create a helper class "SanitizeFileName.cs"
public class SanitizeFileName
{
public static string ReplaceInvalidFileNameChars(string fileName, char? replacement = null)
{
if (fileName != null && fileName.Length != 0)
{
var sb = new StringBuilder();
var badChars = new[] { ',', ' ', '^', '°' };
var inValidChars = Path.GetInvalidFileNameChars().Concat(badChars).ToList();
foreach (var @char in fileName)
{
if (inValidChars.Contains(@char))
{
if (replacement.HasValue)
{
sb.Append(replacement.Value);
}
continue;
}
sb.Append(@char);
}
return sb.ToString();
}
return null;
}
}
Then, use it like this:
var validFileName = SanitizeFileName.ReplaceInvalidFileNameChars(filename, '_');
in my case, i had to clean up the "filename" on the "Content-Deposition" in Response Headers in a c# download method.
Response.AddHeader("Content-Disposition", "attachment;filename=" + validFileName);
精彩评论