C# Sanitize File Name

前端 未结 12 1471
谎友^
谎友^ 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条回答
  •  猫巷女王i
    2020-12-04 06:39

    I think the problem is that you first call Path.GetDirectoryName on the bad string. If this has non-filename characters in it, .Net can't tell which parts of the string are directories and throws. You have to do string comparisons.

    Assuming it's only the filename that is bad, not the entire path, try this:

    public static string SanitizePath(string path, char replaceChar)
    {
        int filenamePos = path.LastIndexOf(Path.DirectorySeparatorChar) + 1;
        var sb = new System.Text.StringBuilder();
        sb.Append(path.Substring(0, filenamePos));
        for (int i = filenamePos; i < path.Length; i++)
        {
            char filenameChar = path[i];
            foreach (char c in Path.GetInvalidFileNameChars())
                if (filenameChar.Equals(c))
                {
                    filenameChar = replaceChar;
                    break;
                }
    
            sb.Append(filenameChar);
        }
    
        return sb.ToString();
    }

提交回复
热议问题