.Net 檔案名稱 資料夾名稱 包含特殊字元去除 .Net 檔案名稱 資料夾名稱 包含特殊字元去除
  .NET       ez      2013-01-25

前一篇已經寫過,使用Path.InvalidPathChars即可達到效果,此篇加強了一些功能,程式如下:

        static void Main(string[] args)
        {
            string FileName = "a:\\abc//[email protected]#$%^&*()_+}{\":?><|.txt...";
            Console.WriteLine(MakeFilenameValid(FileName));
            string FolderName = @"c:\aaa\bbb\ccc\aaa:abc//[email protected]#$%^&*()_+}{:?><|....";
            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

我要留言