How to Remove Illegal Filename Characters in C# and VB.NET

To Remove Illegal Filename Characters in C# and VB.NET you can use the following snippet.

Sample C#

public static string RemoveIllegalFileNameChars(string input, string replacement="")
{
	var regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
	var r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
	return r.Replace(input, replacement);
}

Sample VB.NET

Public Shared Function RemoveIllegalFileNameChars(input As String, Optional replacement As String = "") As String
	Dim regexSearch = New String(Path.GetInvalidFileNameChars()) & New String(Path.GetInvalidPathChars())
	Dim r = New Regex(String.Format("[{0}]", Regex.Escape(regexSearch)))
	Return r.Replace(input, replacement)
End Function

Please rate this snippet

How to check if a folderpath contains Invalid characters

To check if a folderpath contains Invalid characters you can use the following snippet.

Sample C#

public static bool IsValidPathName(string pathName)
{
     return Path.GetInvalidPathChars().All(invalidChar => pathName.Contains(invalidChar) != true);
}

Sample VB.NET

Public Shared Function IsValidPathName(pathName As String) As Boolean
     Return Path.GetInvalidPathChars().All(Function(invalidChar) pathName.Contains(invalidChar) <> True)
End Function

for more informations see the MSDN Path.GetInvalidPathChars Method

Please rate this snippet

How to check if a filepath contains Invalid characters

To check if a filepath contains Invalid characters you can use the following snippet.

Sample C#

public static bool IsValidFilename(string fileName)
{
     return Path.GetInvalidFileNameChars().All(invalidChar => fileName.Contains(invalidChar) != true);
}

Sample VB.NET

Public Shared Function IsValidFilename(fileName As String) As Boolean
     Return Path.GetInvalidFileNameChars().All(Function(invalidChar) fileName.Contains(invalidChar) <> True)
End Function

for more informations see the MSDN Path.GetInvalidFileNameChars Method

Please rate this snippet