C# Sanitize File Name

前端 未结 12 1469
谎友^
谎友^ 2020-12-04 06:06

I recently have been moving a bunch of MP3s from various locations into a repository. I had been constructing the new file names using the ID3 tags (thanks, TagLib-Sharp!),

12条回答
  •  悲哀的现实
    2020-12-04 06:27

    Here's an efficient lazy loading extension method based on Andre's code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace LT
    {
        public static class Utility
        {
            static string invalidRegStr;
    
            public static string MakeValidFileName(this string name)
            {
                if (invalidRegStr == null)
                {
                    var invalidChars = System.Text.RegularExpressions.Regex.Escape(new string(System.IO.Path.GetInvalidFileNameChars()));
                    invalidRegStr = string.Format(@"([{0}]*\.+$)|([{0}]+)", invalidChars);
                }
    
                return System.Text.RegularExpressions.Regex.Replace(name, invalidRegStr, "_");
            }
        }
    }
    

提交回复
热议问题