使用RegEx和递归更改文件名 [英] Changing FileNames using RegEx and Recursion

查看:95
本文介绍了使用RegEx和递归更改文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重命名程序中列出的具有非法字符"的文件,以进行SharePoint文件导入.我指的是非法字符:〜#%& * {}/\ | :<>? -"

I'm trying to rename files that my program lists as having "illegal characters" for a SharePoint file importation. The illegal characters I am referring to are: ~ # % & * {} / \ | : <> ? - ""

我要执行的操作是通过驱动器递归,收集文件名列表,然后通过正则表达式,从列表中选择文件名,然后尝试替换实际文件名中的无效字符.

What i'm trying to do is recurse through the drive, gather up a list of filenames and then through Regular Expressions, pick out file names from a List and try to replace the invalid characters in the actual filenames themselves.

任何人都知道如何执行此操作吗?到目前为止,我有这个:(请记住,我是这个东西的完整n00b)

Anybody have any idea how to do this? So far i have this: (please remember, i'm a complete n00b to this stuff)

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();



    }






}

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

So what i need to figure out is how to recursively search for these invalid chars, replace them in the actual filename itself. Anybody have any ideas?

推荐答案

在递归地处理文件和目录时,使用

When you are working recursively with files and directories, many times it's easier to use the DirectoryInfo class and it's members instead of the static methods. There is a pre-built tree structure for you, so you don't have to manage that yourself.

GetDirectories 返回更多DirectoryInfo实例,以便您可以漫步在树上,而 GetFiles 返回 FileInfo 对象.

GetDirectories returns more DirectoryInfo instances so you can walk the tree, while GetFiles returns FileInfo objects.

此人创建了一个自定义迭代器递归地产生文件信息,将其与现有的regex工作结合使用,即可完成您的解决方案.

This guy created a custom iterator to recursively yield file info, which when you combine it with your existing regex work, would complete your solution.

这篇关于使用RegEx和递归更改文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆