Scenario:
Sharepoint imposes some restriction on the file and folder names . Also it doesn't allow some special characters in the file / folder name.
Solution:
Here's a quick fix to the file / folder name change using Regular expression.
Note : I am replacing the special characters with underscore and not with space because one space translate to %20 and occupies three character space in Url.
Code:
using System.Text.RegularExpressions;
private string CleanUpSpecialCharacters(string fileName)
{
string fileTitle = fileName.Substring(0, fileName.LastIndexOf("."));
string fileExtenstion = fileName.Substring(fileName.LastIndexOf("."));
string pattern = @"[#%&*:<>?/{|}/\\.]";
Regex rgx = new Regex(pattern);
// Replace runs of white space in the input string with a
// underscore.
string newfileTitle = rgx.Replace(fileTitle, "_");
return string.Concat(newfileTitle, fileExtenstion);
}
private string Truncate(string fileName)
{
if (fileName.Length > 127)
return fileName.Substring(0, 127);
else
return fileName;
}
2 comments:
the namespace for regular expressions is RegularExpressions (not RegularExpression)
I needed a stronger truncation by appending long file name with time ticks to provide unique file names. Basically an adaptation of yours routine. Adapt or alter if you need. Thanks, RussEbbing@yahoo.com
private static string CleanUpSpecialCharacters(string fileName)
{
string fileTitle = fileName.Substring(0, fileName.LastIndexOf("."));
string fileExtenstion = fileName.Substring(fileName.LastIndexOf("."));
string pattern = @"[#%&*:<>?/{|}/\\.]";
Regex rgx = new Regex(pattern);
// Replace runs of white space in the input string with a
// underscore.
string newfileTitle = rgx.Replace(fileTitle, "_");
return string.Concat(newfileTitle, fileExtenstion);
}
private static string TruncateFileName(string fileName, bool appendTicks)
{
const int maxFileLength = 127;
if (fileName.Length <= maxFileLength)
return fileName;
else
{
string fileTitle = fileName.Contains(".") ? fileName.Substring(0, fileName.LastIndexOf(".")) : fileName;
string fileExtenstion = fileName.Contains(".") ? fileName.Substring(fileName.LastIndexOf(".")) : string.Empty;
string ticks = appendTicks ? "_t" + DateTime.Now.Ticks.ToString() : string.Empty;
fileName = fileTitle.Substring(0, maxFileLength - ticks.Length - fileExtenstion.Length) + ticks + fileExtenstion;
Debug.Assert(fileName.Length == maxFileLength);
return fileName;
}
}
Post a Comment