Skip to main content
 首页 » 编程设计

c#之如果目录中已存在文件夹,如何增加文件夹编号

2024年02月20日12bonelee

例。如果我创建了一个文件夹名称为 IMG10001 的文件夹,但它已经存在于目标目录中。下面的代码将使文件夹名称为 IMG10001-1,但我想完成的是如果 IMG10001 已存在于目标目录中,则将文件夹名称递增为 IMG10002。

string destinDir = dirPath + "\\" + this.Batch.BatchName; 
int x = 0; 
if (Directory.Exists(destinDir)) 
{ 
    do 
    { 
        x++; 
        destinDir = dirPath + "\\" + this.Batch.BatchName + "-" + x.ToString(); 
    } while (Directory.Exists(destinDir)); 
}     
System.IO.Directory.Move(root,destinDir); 

请您参考如下方法:

//regular expression will work 
Regex reg = new Regex("IMG(\\d+)$"); 
Match m = reg.match(this.Batch.BatchName); 
int num = 10001; 
if(m.success){ 
    int.tryParse(m.Groups[1].value,out num); 
} 
Return string.format("IMG{0}",num); 

我只是把这些代码写在输入框里,没试过。但我认为它应该有效