请注意:这是一个代码问题而非系统操作一。使用RegEx重命名文件夹
我有几个drilldowns(基本上是一个文件夹内的文件夹内的文件夹...)的文件夹。我想知道如果有人知道如何使用RegEx重命名文件夹名称?基本上我需要摆脱〜“#%& *:<>?/\ {| }在任何文件夹名称。我想知道如何做到这一点,因为我认为我需要从“底部”开始(意思是最后一个可能的向下钻取文件夹,并开始从最底层到最高层重新命名文件夹)。
有人有什么想法吗?
所以我有下面这段代码:
public partial class CleanPathResults : Form
{
public CleanPathResults()
{
InitializeComponent();
}
public void Sanitizer(List<string> dirtyPaths)
{
string regPattern = (@"[~#&!%+{}]+");
string replacement = " ";
Regex regExPattern = new Regex(regPattern);
Regex regExPattern2 = new Regex(@"\s{2,}");
StreamWriter errors = new StreamWriter(@"S:\test\Errors.txt", true);
var dirCount = new Dictionary<string, int>();
dataGridView1.Rows.Clear();
try
{
foreach (string invalidPaths in dirtyPaths)
{
string sanitizedPath = regExPattern.Replace(invalidPaths, replacement);
sanitizedPath = regExPattern2.Replace(sanitizedPath, replacement);
DataGridViewRow clean = new DataGridViewRow();
clean.CreateCells(dataGridView1);
clean.Cells[0].Value = invalidPaths;
clean.Cells[1].Value = sanitizedPath;
dataGridView1.Rows.Add(clean);
System.IO.Directory.Move(invalidPaths, sanitizedPath);
}
}
catch (Exception e)
{
throw;
//errors.Write(e);
}
}
我面对这里最大的问题是,这些路径需要从最低级别的文件夹重命名为最高级别的文件夹或我会继续加油在调试过程中抛出错误。
我的问题是如何钻入驱动器,转到树视图中的最低文件夹,向上重命名文件夹? 以路径为例:G:\ Test〜\这只是一个测试\测试&测试\测试!! \ ## test.txt
我怎么能够重命名这个,并从测试!文件夹和工作我的方式,以便我不会有任何错误?
但是我在第一个foreach循环中试过这个,我的文件夹名没有GetDirectories()方法。这不仅仅是为了文件吗? – yeahumok 2010-07-14 20:12:55
@yeahumok:你是说这个没有编译,或者你发送的DirectoryInfo对象没有子文件夹? – 2010-07-15 13:28:14