August 07, 2014

How to Covert string to valid file name format, get valid file name, file name validation

This is general question that How to Covert string to a file name to save on drive or some location. our Keyboard have so many special characters and looking for more symbols in our keyboard,
That's good for users but for developers its headache coz out of those characters few are allowed in file name,
That makes issue sometime while reading/writing or creating file.

if user entered some incorrect word so instead of giving error to end user we can replace all those special characters by any specific character like I have done with char '_' underscore,
The file name is very important in terms of search or crawl files/file name.


So to make it simple, easy and working I have would prefer to use below way to do so.....


C# Code:
private string ConverToStandardFileName(string accountName)
        {
            foreach (char c in System.IO.Path.GetInvalidFileNameChars())
            {
                accountName = accountName.Replace(c, '_');
            }
            return accountName;
        }


That can be used in any aspx or C#/Windows appliaction. Other ways are also suggested over internet like .Replace("%","").Replace("&",""),Replace("*","") etc....


Other ways/suggestion are welcome, also shared you findings on this.


--

Regards,
Praveen Pandit
Keep Sharing Knowledge!!

No comments:

Post a Comment