पर मिले आप की जाँच करने के लिए जो स्ट्रिंग के पात्रों अमान्य हैं Path.GetInvalidFileNameChars उपयोग कर सकते हैं, और या तो इस तरह के एक हायफ़न या के रूप में एक वैध चार करने के लिए उन्हें बदलने (यदि आप द्विदिश रूपांतरण की जरूरत है) द्वारा उन्हें स्थानापन्न %
जैसे बचने वाले टोकन ने अपने यूनिकोड कोड के हेक्साडेसिमल प्रतिनिधित्व के बाद (मैंने वास्तव में इस तकनीक का उपयोग किया है लेकिन अभी कोड नहीं है)।
संपादित करें: बस अगर कोई दिलचस्पी लेता है, तो कोड है।
/// <summary>
/// Escapes an object name so that it is a valid filename.
/// </summary>
/// <param name="fileName">Original object name.</param>
/// <returns>Escaped name.</returns>
/// <remarks>
/// All characters that are not valid for a filename, plus "%" and ".", are converted into "%uuuu", where uuuu is the hexadecimal
/// unicode representation of the character.
/// </remarks>
private string EscapeFilename(string fileName)
{
char[] invalidChars=Path.GetInvalidFileNameChars();
// Replace "%", then replace all other characters, then replace "."
fileName=fileName.Replace("%", "%0025");
foreach(char invalidChar in invalidChars)
{
fileName=fileName.Replace(invalidChar.ToString(), string.Format("%{0,4:X}", Convert.ToInt16(invalidChar)).Replace(' ', '0'));
}
return fileName.Replace(".", "%002E");
}
/// <summary>
/// Unescapes an escaped file name so that the original object name is obtained.
/// </summary>
/// <param name="escapedName">Escaped object name (see the EscapeFilename method).</param>
/// <returns>Unescaped (original) object name.</returns>
public string UnescapeFilename(string escapedName)
{
//We need to temporarily replace %0025 with %! to prevent a name
//originally containing escaped sequences to be unescaped incorrectly
//(for example: ".%002E" once escaped is "%002E%0025002E".
//If we don't do this temporary replace, it would be unescaped to "..")
string unescapedName=escapedName.Replace("%0025", "%!");
Regex regex=new Regex("%(?<esc>[0-9A-Fa-f]{4})");
Match m=regex.Match(escapedName);
while(m.Success)
{
foreach(Capture cap in m.Groups["esc"].Captures)
unescapedName=unescapedName.Replace("%"+cap.Value, Convert.ToChar(int.Parse(cap.Value, NumberStyles.HexNumber)).ToString());
m=m.NextMatch();
}
return unescapedName.Replace("%!", "%");
}
यह * बिल्कुल * क्यों है, मैं एक साधारण रेगेक्स प्रतिस्थापन के साथ अपना खुद का रोलिंग क्यों नहीं करना चाहता था। धन्यवाद। –