public static string ConvertToValidUrlFileName(string leafName, char charToReplaceInvalidChar) { if (string.IsNullOrEmpty(leafName)) { throw new ArgumentNullException("leafName"); } if (SPUrlUtility.IsLegalFileName(leafName)) { return(leafName); } StringBuilder stringBuilder = new StringBuilder(); if (charToReplaceInvalidChar != 0 && !SPUrlUtility.IsLegalCharInUrl(charToReplaceInvalidChar)) { charToReplaceInvalidChar = '\0'; } bool flag = charToReplaceInvalidChar != '\0'; string text = leafName.Trim().Trim('.'); char c = '\0'; bool flag2 = false; char[] array = text.ToCharArray(); foreach (char c2 in array) { if (!SPUrlUtility.IsLegalCharInUrl(c2) || (c2 == '.' && c == '.')) { flag2 = true; } else { if (flag2 && flag) { stringBuilder.Append(charToReplaceInvalidChar); flag2 = false; } stringBuilder.Append(c2); c = c2; } } return(stringBuilder.ToString()); }