Sunday 22 November 2015

How to Covert invalid file name to valid file name format, with unique file name, get valid file name, file name validation


The most common piece of code we used to put for file name validation before uploading, we need to remove invalid characters as well made the same file as unique file name by appending Current DateTime string.  

Now lets's see how to get desired file name to save on drive or some location.


Problem The Keyboard have hell lot of special characters and few of them are invalid. 
That makes issue sometime for application developer while writing or creating file.



Solution 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. 


private string GetValideUniqueFileName(string fileName)
        {
            char[] additionalInvalidSharePointSpecialCharacters = new char[8] { '~', '#', '%', '&', '{', '}', '+', ' ' };
            char[] defaulChars = System.IO.Path.GetInvalidFileNameChars();

            defaulChars = defaulChars.Concat(additionalInvalidSharePointSpecialCharacters).ToArray();

            foreach (char item in defaulChars)
            {
                fileName = fileName.Replace(item, '_');
            }
            
 string name = string.Format ("{0}_{1}{2}",System.IO.Path.GetFileNameWithoutExtension(fileName),
     DateTime.Now.ToString("yyyy-MM-dd-hh_mm_ss"),
     System.IO.Path.GetExtension(fileName))

            return name;
        }


Any better solution or enhancement needed here, so put your thoughts in comment box

No comments:

Post a Comment