Search This Blog

January 28, 2010

Checking for invalid file name and filepath

Following method verifies the given file name for invalid characters and returns the valid filename.


///
/// Verifies if invalid character is present in the filename
/// If invalid character is present it replaces with replace character.
///

/// fileName to validated
/// replace character for invalid character
/// valid filename
public static string ModifyInvalidFileName(string fileName, string replaceChar)
{
if (string.IsNullOrEmpty(fileName))
{
return fileName;
}
if (string.IsNullOrEmpty(replaceChar))
{
replaceChar = "";
}
string strFileName = fileName;
char[] invalidFileNameChars = System.IO.Path.GetInvalidFileNameChars();
int invalidPresent = strFileName.IndexOfAny(invalidFileNameChars);
if (invalidPresent > -1)
{
foreach (char invalidChar in invalidFileNameChars)
{
strFileName = strFileName.Replace(invalidChar.ToString(), replaceChar);
}
}
return strFileName;
}



We can use GetInvalidFileNameChars from System.IO namespace to identify all the invalid characters in the File Name. Check the following link for more details. If we use the built-in C#.net methods it will check for all the invalid characters and no need to identify each charcter by us.

getinvalidfilenamechars

To verify the invalid Path we can use the GetInvalidPathChars() method.

GetInvalidPathChars

No comments: