【问题标题】:Changing FileNames using RegEx and Recursion使用 RegEx 和递归更改文件名
【发布时间】:2011-03-02 06:03:49
【问题描述】:

我正在尝试重命名我的程序列出的具有“非法字符”的文件以用于 SharePoint 文件导入。我指的非法字符是: ~ # % & * {} / \ | :? - ""

我正在尝试做的是通过驱动器递归,收集文件名列表,然后通过正则表达式,从列表中挑选文件名并尝试替换实际文件名本身中的无效字符。

有人知道怎么做吗?到目前为止,我有这个:(请记住,我对这些东西完全不了解)

class Program
{
    static void Main(string[] args)
    {
        string[] files = Directory.GetFiles(@"C:\Documents and Settings\bob.smith\Desktop\~Test Folder for [SharePoint] %testing", "*.*", SearchOption.AllDirectories);
        foreach (string file in files)
        {
            Console.Write(file + "\r\n");


        }
        Console.WriteLine("Press any key to continue...");
        Console.ReadKey(true);



        string pattern = " *[\\~#%&*{}/:<>?|\"-]+ *";
        string replacement = " ";
        Regex regEx = new Regex(pattern);

        string[] fileDrive = Directory.GetFiles(@"C:\Documents and Settings\bob.smith\Desktop\~Test Folder for [SharePoint] %testing", "*.*", SearchOption.AllDirectories);
        StreamWriter sw = new StreamWriter(@"C:\Documents and Settings\bob.smith\Desktop\~Test Folder for [SharePoint] %testing\File_Renames.txt");
        foreach(string fileNames in fileDrive)
        {

        string sanitized = regEx.Replace(fileNames, replacement);
        sw.Write(sanitized + "\r\n");
        }
        sw.Close();



    }






}

所以我需要弄清楚的是如何递归搜索这些无效字符,将它们替换为实际文件名本身。有人有什么想法吗?

【问题讨论】:

  • 我认为他只是想把它们撕掉
  • 正则表达式是否符合您的要求?

标签: c# regex file renaming


【解决方案1】:

当您以递归方式处理文件和目录时,很多时候使用DirectoryInfo 类及其成员而不是静态方法更容易。有一个为您预先构建的树结构,因此您不必自己管理它。

GetDirectories 返回更多 DirectoryInfo 实例,以便您可以遍历树,而 GetFiles 返回 FileInfo 对象。

这个人 created a custom iterator 递归生成文件信息,当您将其与现有的正则表达式工作结合时,将完成您的解决方案。

【讨论】:

  • 我查看了自定义迭代器链接。我在哪里传递我想钻入的目录?
  • GetFilesRecursive(dirInfo); -- 只传递一个根目录信息
【解决方案2】:

File.Move() 有效地重命名文件。基本上,你只需要

File.Move(fileNames, sanitized);

在后一个循环中。

警告 - 可能会有重复的文件名,因此您必须制定策略来避免这种情况,例如在 sanitized 变量的末尾附加一个计数器。另外,应用适当的异常处理。

PS:当然,你不需要搜索:\*之类的字符。

【讨论】:

  • 我需要在此处添加 if/else 语句吗?或者如果文件没有无效字符,它会自动跳过它?
  • @yeahumok,您确实可以将fileNamessanitized 进行比较,以避免不必要地调用File.Move()。但是,请注意重复(例如,#File.txt~File.txt 将被命名为 File.txt),并检查访问权限、磁盘空间和其他 IO 异常。
猜你喜欢
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-15
  • 2014-08-11
相关资源
最近更新 更多