2017-07-24 137 views
0

我做了一個程序,重命名文件夾中的文件,它的工作原理,但有一個問題,如果我添加更多的文件,然後重命名它與覆蓋其他文件的程序,所以我已嘗試if(!File.Exists),但它一直不工作。任何人都可以幫助if(!File.Exists)部分? CUS這一個不工作始終返回trueC#File.exists路徑

Console.WriteLine("1. Rename all\n2. Rename Custom"); 
int Choice = int.Parse(Console.ReadLine()); 
Console.Clear(); 
if(Choice==1) 
{ 
    Console.WriteLine("Enter the file path:"); 
    string path = Console.ReadLine(); 
    Console.WriteLine("Enter the new file type"); 
    string type = Console.ReadLine(); 
    DirectoryInfo d = new DirectoryInfo(@path); 
    FileInfo[] infos = d.GetFiles("*.*"); 
    int i = 1; 
    foreach (FileInfo f in infos) 
    { 
     // Do the renaming here 
     if (!File.Exists(@path+i+"."+type)) 
     File.Move(f.FullName, Path.Combine(f.DirectoryName, "" + i + "." + type)); 
     i++; 
    } 
} 

回答

4

首先,你不需要@pathpath沒有@將工作得很好。其次,您檢查存在的文件與移動的目標路徑不匹配。試試這個:

string destination = Path.Combine(f.DirectoryName, string.Format("{0}.{1}", i, type)); 
if (!File.Exists(destination)) 
{ 
    File.Move(f.FullName, destination); 
    i++; // Unclear if you want this to increment every time or just when moving 
}