1

我正在尝试重命名我的程序列出的具有“非法字符”的文件以用于 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();



    }






}

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

4

2 回答 2

1

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

File.Move(fileNames, sanitized);

在后一个循环内。

ALERT - 可能会有重复的文件名,所以你必须建立一个策略来避免这种情况,比如在sanitized变量的末尾附加一个计数器。此外,应用适当的异常处理。

PS:当然,你不需要搜索像:\*.

于 2010-06-10T15:50:52.463 回答
1

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

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

这个人创建了一个自定义迭代器来递归地产生文件信息,当你将它与现有的正则表达式工作结合起来时,将完成你的解决方案。

于 2010-06-10T15:57:41.263 回答