How to generate a valid SharePoint FileName

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

2 thoughts on “How to generate a valid SharePoint FileName”

  1. 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é

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Share via
Copy link
Powered by Social Snap