C# Sanitize File Name

前端 未结 12 1434
谎友^
谎友^ 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:23

    I'm using the System.IO.Path.GetInvalidFileNameChars() method to check invalid characters and I've got no problems.

    I'm using the following code:

    foreach( char invalidchar in System.IO.Path.GetInvalidFileNameChars())
    {
        filename = filename.Replace(invalidchar, '_');
    }
    
    0 讨论(0)
  • 2020-12-04 06:24

    Your code would be cleaner if you appended the directory and filename together and sanitized that rather than sanitizing them independently. As for sanitizing away the :, just take the 2nd character in the string. If it is equal to "replacechar", replace it with a colon. Since this app is for your own use, such a solution should be perfectly sufficient.

    0 讨论(0)
  • 2020-12-04 06:24
    using System;
    using System.IO;
    using System.Linq;
    using System.Text;
    
    public class Program
    {
        public static void Main()
        {
            try
            {
                var badString = "ABC\\DEF/GHI<JKL>MNO:PQR\"STU\tVWX|YZA*BCD?EFG";
                Console.WriteLine(badString);
                Console.WriteLine(SanitizeFileName(badString, '.'));
                Console.WriteLine(SanitizeFileName(badString));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }
    
        private static string SanitizeFileName(string fileName, char? replacement = null)
        {
            if (fileName == null) { return null; }
            if (fileName.Length == 0) { return ""; }
    
            var sb = new StringBuilder();
            var badChars = Path.GetInvalidFileNameChars().ToList();
    
            foreach (var @char in fileName)
            {
                if (badChars.Contains(@char)) 
                {
                    if (replacement.HasValue)
                    {
                        sb.Append(replacement.Value);
                    }
                    continue; 
                }
                sb.Append(@char);
            }
            return sb.ToString();
        }
    }
    
    0 讨论(0)
  • 2020-12-04 06:26

    A shorter solution:

    var invalids = System.IO.Path.GetInvalidFileNameChars();
    var newName = String.Join("_", origFileName.Split(invalids, StringSplitOptions.RemoveEmptyEntries) ).TrimEnd('.');
    
    0 讨论(0)
  • 2020-12-04 06:27

    To clean up a file name you could do this

    private static string MakeValidFileName( string name )
    {
       string invalidChars = System.Text.RegularExpressions.Regex.Escape( new string( System.IO.Path.GetInvalidFileNameChars() ) );
       string invalidRegStr = string.Format( @"([{0}]*\.+$)|([{0}]+)", invalidChars );
    
       return System.Text.RegularExpressions.Regex.Replace( name, invalidRegStr, "_" );
    }
    
    0 讨论(0)
  • 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, "_");
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题