Skip to main content
 首页 » 编程设计

c#之现有文件名和创建唯一文件名的问题

2024年02月24日35fff_TT

我有这个代码:

public void FileCleanup(List<string> paths) 
    { 
        string regPattern = (@"[~#&!%+{}]+"); 
        string replacement = ""; 
        string replacement_unique = "_"; 
        Regex regExPattern = new Regex(regPattern); 
        List<string> existingNames = new List<string>(); 
        StreamWriter errors = new StreamWriter(@"C:\Documents and Settings\jane.doe\Desktop\SharePointTesting\Errors.txt"); 
        StreamWriter resultsofRename = new StreamWriter(@"C:\Documents and Settings\jane.doe\Desktop\SharePointTesting\Results of File Rename.txt"); 
        foreach (string files2 in paths) 
 
            try 
            { 
                string filenameOnly = Path.GetFileName(files2); 
                string pathOnly = Path.GetDirectoryName(files2); 
                string sanitizedFileName = regExPattern.Replace(filenameOnly, replacement); 
                string sanitized = Path.Combine(pathOnly, sanitizedFileName); 
                if (!System.IO.File.Exists(sanitized)) 
                { 
                    existingNames.Add(sanitized); 
                    try 
                    { 
                        foreach (string names in existingNames) 
                        { 
                            string filename = Path.GetFileName(names); 
                            string filepath = Path.GetDirectoryName(names); 
                            string cleanName = regExPattern.Replace(filename, replacement_unique); 
                            string scrubbed = Path.Combine(filepath, cleanName); 
                            System.IO.File.Move(names, scrubbed); 
                            //resultsofRename.Write("Path: " + pathOnly + " / " + "Old File Name: " + filenameOnly + "New File Name: " + sanitized + "\r\n" + "\r\n"); 
                            resultsofRename = File.AppendText("Path: " + filepath + " / " + "Old File Name: " + filename + "New File Name: " + scrubbed + "\r\n" + "\r\n"); 
 
                        } 
                    } 
                    catch (Exception e) 
                    { 
                        errors.Write(e); 
                    } 
 
                } 
                else 
                { 
                    System.IO.File.Move(files2, sanitized); 
                    resultsofRename.Write("Path: " + pathOnly + " / " + "Old File Name: " + filenameOnly + "New File Name: " + sanitized + "\r\n" + "\r\n"); 
                } 
 
 
            } 
            catch (Exception e) 
            { 
                //write to streamwriter 
            } 
       } 
   } 
} 

我在这里要做的是通过删除无效字符(在正则表达式中定义)来重命名“脏”文件名,将它们替换为“”。但是,我注意到如果我有重复的文件名,应用程序不会重命名它们。 IE。如果我在同一个文件夹中有##test.txt 和~~test.txt,它们将被重命名为test.txt。因此,我创建了另一个 foreach 循环,它用“_”而不是空格替换无效字符。

问题是,每当我尝试运行它时,什么都没有发生!所有文件都没有重命名!

有人可以告诉我我的代码是否不正确以及如何修复吗?

另外——有人知道我如何每次用不同的字符替换第二个 foreach 循环中的无效字符吗?这样,如果有多个实例,即 %Test.txt、~Test.txt 和#test.txt(全部重命名为 test.txt),它们可以以某种方式用不同的字符唯一命名?

请您参考如下方法:

However, would you know how to replace the invalid char with a different unique character every time so that each filename remains unique?

这是一种方式:

char[] uniques = ",'%".ToCharArray(); // whatever chars you want 
foreach (string file in files) 
{ 
    foreach (char c in uniques) 
    { 
        string replaced = regexPattern.Replace(file, c.ToString());  
        if (File.Exists(replaced)) continue; 
        // create file 
    } 
} 

您当然可能希望将其重构为它自己的方法。另请注意,仅唯一字符不同的文件的最大数量限制为 uniques 数组中的字符数,因此如果您有很多具有相同名称的文件只是特殊字符不同您列出的字符,使用不同的方法可能是明智的,例如在文件名末尾附加一个数字。

how would i append a digit to the end of the file name (with a different # everytime?)

Josh 建议的稍微修改版本可以跟踪修改后的文件名映射到替换后生成相同文件名的次数:

var filesCount = new Dictionary<string, int>(); 
string replaceSpecialCharsWith = "_"; // or "", whatever 
foreach (string file in files) 
{ 
    string sanitizedPath = regexPattern.Replace(file, replaceSpecialCharsWith); 
    if (filesCount.ContainsKey(sanitizedPath)) 
    { 
        filesCount[file]++; 
    } 
    else  
    { 
        filesCount.Add(sanitizedPath, 0); 
    } 
 
    string newFileName = String.Format("{0}{1}{2}",  
                Path.GetFileNameWithoutExtension(sanitizedPath),  
                filesCount[sanitizedPath] != 0  
                     ? filesCount[sanitizedPath].ToString()  
                     : "",  
                Path.GetExtension(sanitizedPath)); 
 
    string newFilePath = Path.Combine(Path.GetDirectoryName(sanitizedPath), 
                                       newFileName); 
    // create file... 
}