title: FileInfo.MoveTo if file exists - rename
body: <p>I have an application that moves files from one directory to another, but sometimes a conflict occurs and the file already exists in the destination directory.</p>
  
  <p>When that happens, I want to move the file with a different name - e.g. if the file is named <code>test.txt</code>, I want to name it <code>test.txt.1</code>. That's okay, but how do I do it next time, if the file is again <code>test.txt</code>, but in the destination folder we have both <code>test.txt</code> and <code>test.txt.1</code>.</p>
  
  <p>My problem is that I can't find the last created file so that I can read its index and increment it with 1. Any suggestions?</p>
  
  <pre><code>string sourcePath = "C:\\Files\\test.txt";
  string filename = Path.GetFileName(sourcePath);
  string pathTo = "C:\\Files\\test\\" + filename;
  
  try
  {
      var fileInfo = new FileInfo(sourcePath);
      fileInfo.MoveTo(pathTo);
  }
  catch (IOException ex)
  {
      var fileInfo = new FileInfo(sourcePath);
      var file = Directory.GetFiles(pathTo, filename+".1").FirstOrDefault();
      if (file == null)
      {
          fileInfo.MoveTo(pathTo+".1");
      }
      else
      {
          //find the old file, read it's last index and increment it with 1
      }
  
  }
  </code></pre>