System.IO.IOException help

Eduardo Gomez 3,651 Reputation points
2022-01-14T00:22:49.8+00:00

I have this code

using Microsoft.VisualBasic.FileIO;  
  
DirectoryInfo d = new DirectoryInfo(@"C:\Users\egome\OneDrive - Universidad Politécnica de Madrid\Desktop\speckyboy-free-avatar-icon-set\SVG\1 de 3 Avatars FLAT");  
FileInfo[] infos = d.GetFiles();  
foreach (FileInfo f in infos) {  
    FileSystem.RenameFile(f.FullName, f.Name.Remove(0, 3));  
}  

I got this error

System.IO.IOException: 'Could not complete operation since a file already exists in this path 'C:\Users\egome\OneDrive - Universidad Politécnica de Madrid\Desktop\speckyboy-free-avatar-icon-set\SVG\1 de 3 Avatars FLAT\mexican.svg'.'

this is happening because164889-screenshot-2022-01-13-233603.png164982-screenshot-2022-01-14-000025.png164878-screenshot-2022-01-14-000306.png I have duplicates names

But the this is I just want to remove the XX-
I do not care if is duplicated, I want the duplicated

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,161 Reputation points
    2022-01-14T03:32:36.257+00:00

    Seems like a duplicate post of this.

    The issue is when you strip off the XX- from some files you are left with a file name that already exists. How exactly do you want to deal with the dups? You cannot have 2 files in the same folder with the same name. It isn't allowed. Perhaps you want to add a (1) to the filename.

       var files = Directory.GetFiles(@"C:\Users\egome\OneDrive - Universidad Politécnica de Madrid\Desktop\speckyboy-free-avatar-icon-set\SVG\1 de 3 Avatars FLAT"))  
       foreach (var file in files)  
       {  
          //Assuming all files begin with XX- here...  
          var adjustedName = Path.GetFileName(file).Remove(0, 3);  
         
          //Ensure unique  
          var index = 1;  
          var newName = adjustedName;  
          while (File.Exists(newName))  
          {  
              newName = adjustedName + $" ({index}++)";  
          };  
         
          File.Move(file, Path.Combine(Path.GetDirectoryName(file), newName), true);  
       }  
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.