【问题标题】:C# File.exists pathC# File.exists 路径
【发布时间】:2017-07-24 22:43:24
【问题描述】:

我制作了一个重命名文件夹中文件的程序,它可以工作,但是有一个问题,如果我添加更多文件然后用程序重命名它会覆盖其他文件,所以我尝试了if(!File.Exists)但它一直不起作用。任何人都可以提供if(!File.Exists) 部分的帮助吗?因为这个不起作用并且总是返回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++;
   }   
}

【问题讨论】:

    标签: c# .net file c#-4.0


    【解决方案1】:

    首先,您不需要@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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多