可以用以下代码解决:
private static string NormalizeFileName(string fileName)
{
try
{
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"(?<HEX>%\d{2})");
System.Text.RegularExpressions.MatchCollection matches = regex.Matches(fileName);
Dictionary<string, char> mappingTable = new Dictionary<string, char>();
foreach (System.Text.RegularExpressions.Match match in matches)
{
if (!match.Success)
{
return fileName;
}
string matchStr = match.Value;
if (!mappingTable.ContainsKey(matchStr))
{
mappingTable.Add(matchStr, HexToChar(matchStr.Substring(1)));
}
}
if (mappingTable.Keys.Count == 0)
{
return fileName;
}
string normalizedFileName = fileName;
foreach (KeyValuePair<string, char> keyValuePair in mappingTable)
{
normalizedFileName = normalizedFileName.Replace(keyValuePair.Key, keyValuePair.Value.ToString());
}
if (normalizedFileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
{
return fileName;
}
return normalizedFileName;
}
catch
{
return fileName;
}
}
private static char HexToChar(string hexValue)
{
if (hexValue.Length != 2)
{
throw new ArgumentException("hexValue parameter must have two chars");
}
return (char)Convert.ToInt32(hexValue, 16);
} |