Monday, 4 November 2013

C# Remove Invalid filename characters from string

Ever wanted to remove invalid filename characters from a string while dealing with file related code?
Here is a pretty easy solution using C# Regex class.
The funda is to find any invalid character/characters from the string and remove it.
Here is the method which does the trick.
private static string GetValidFileName(string fileName)
{
// remove any invalid character from the filename.
return Regex.Replace(fileName.Trim(), "[^A-Za-z0-9_. ]+", "");
}
The code even preserves white spaces and removes only invalid special characters. The Regex patter can also be replaced by "[^a-zA-Z 0-9'.@]" A better solution which I prefer is using LINQ:
private static string GetValidFileName(string fileName)
{
return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
}
There is a solution mentioned in MSDN which personally I do not find very appealing.
static string CleanInput(string strIn)
{
 // Replace invalid characters with empty strings. 
 try {
    return Regex.Replace(strIn, @"[^\w\.@-]", "", 
       RegexOptions.None, TimeSpan.FromSeconds(1.5)); 
 }
 // If we timeout when replacing invalid characters,  
 // we should return Empty. 
 catch (RegexMatchTimeoutException) {
    return String.Empty;   
 }
}

4 comments: