.NET ez 2013-01-25
前一篇已經寫過,使用Path.InvalidPathChars即可達到效果,此篇加強了一些功能,程式如下:
static void Main(string[] args)
{
string FileName = "a:\\abc//~!@#$%^&*()_+}{\":?><|.txt...";
Console.WriteLine(MakeFilenameValid(FileName));
string FolderName = @"c:\aaa\bbb\ccc\aaa:abc//~!@#$%^&*()_+}{:?><|....";
Console.WriteLine(MakeFoldernameValid(FolderName));
Console.Read();
}
static string MakeFilenameValid(string FN)
{
if (FN == null) throw new ArgumentNullException();
if (FN.EndsWith(".")) FN = Regex.Replace(FN, @"\.+$", "");
if (FN.Length == 0) throw new ArgumentException();
if (FN.Length > 245) throw new PathTooLongException();
foreach (char c in System.IO.Path.GetInvalidFileNameChars()) FN = FN.Replace(c, '_');
return FN;
}
static string MakeFoldernameValid(string FN)
{
if (String.IsNullOrEmpty(FN)) throw new ArgumentNullException();
if (FN.EndsWith(".")) FN = Regex.Replace(FN, @"\.+$", "");
if (FN.Length == 0) throw new ArgumentException();
if (FN.Length > 245) throw new PathTooLongException();
foreach (char c in System.IO.Path.GetInvalidPathChars()) FN = FN.Replace(c, '_');
return FN.Replace("/", @"\");
}標籤: .NET
本文章網址:
https://www.ez2o.com/Blog/Post/csharp-File-Special-Char-Remove
https://www.ez2o.com/Blog/Post/313
https://www.ez2o.com/Blog/Post/csharp-File-Special-Char-Remove
https://www.ez2o.com/Blog/Post/313
