簡體   English   中英

C#File.exists路徑

[英]C# File.exists path

我已經制作了一個程序來重命名文件夾中的文件,並且它可以工作,但是有一個問題,如果我添加更多文件,然后使用該程序重命名它會覆蓋其他文件,所以我嘗試了if(!File.Exists)但仍然無法正常工作。 任何人都可以幫助if(!File.Exists)部分嗎? cus this this不起作用,總是返回true

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++;
   }   
}

首先,您不需要@path 沒有@ path將正常工作。 其次,您要檢查的文件是否與移動的目標路徑不匹配。 嘗試以下方法:

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM