How to generate a valid SharePoint FileName

By Namwar Rizvi - Last updated: Thursday, June 17, 2010 - Save & Share - 2 Comments

SharePoint imposes several restrictions for the filenames. To get the details of all these restrictions, please check this support article from Microsoft. I have created a utility function to convert a given string to a valid SharePoint filename. This function is valid for SharePoint 2003, 2007 and 2010. Here you go

public string ConvertToValidSharePointFileName(string originalFileName)
{
char[] InvalidFilenameCharacters = new[] {'\\', '/', ':', '*', '?', '"', '<', '>', '|', '#', '{', '}', '%', '~','&' };
string[] InvalidFileNameStrings = new[] { ".files", "_files",
"-Dateien", "_fichiers", "_bestanden","_file",
"_archivos", "-filer", "_tiedostot", "_pliki",
"_soubory","_elemei", "_ficheiros", "_arquivos",
"_dosyalar", "_datoteke","_fitxers", "_failid",
"_fails", "_bylos", "_fajlovi", "_fitxategiak"};

string validSharePointFileName = originalFileName;

//Remove Invalid characters
validSharePointFileName = validSharePointFileName.Remove(InvalidFilenameCharacters);

//Remove consecutive periods(..)
while (validSharePointFileName.Contains(".."))
{
validSharePointFileName = validSharePointFileName.Replace("..", ".");
}

//Remove reserved words from end
foreach (string s in InvalidFileNameStrings)
{
if (validSharePointFileName.EndsWith(s))
{
if (validSharePointFileName.Length > s.Length)
{
validSharePointFileName = validSharePointFileName.Substring(0, validSharePointFileName.Length - s.Length);
}
}
}

//Remove period (.) at end
if (validSharePointFileName.EndsWith("."))
{
validSharePointFileName = validSharePointFileName.Remove(validSharePointFileName.Length - 1, 1);
}

//Remove period (.) at end
if (validSharePointFileName.StartsWith("."))
{
validSharePointFileName = validSharePointFileName.Remove(0, 1);
}

return validSharePointFileName;
}
Share
Posted in C#, Solutions, SP2010, Tips • Tags: , , , , Top Of Page

2 Responses to “How to generate a valid SharePoint FileName”

Comment from Jose Dias
Time April 10, 2013 at 2:23 pm

Hi,

what would be your for best-practice on how to use this function.

Is it something that can be added into the
SharePoint File (Bilk-)Upload-Process?

Thanks in advance for your support!

Best regards,
José

Comment from User
Time September 26, 2013 at 6:05 am

Fix in source ‘<‘, ‘>’, ‘&’ to ”, ‘&’.

Write a comment