Glenn singh
Glenn singh

Reputation: 263

How to rename multiple files after specific character in C#?

I am trying to rename multiple files in C# after specific character.
In my folder I have these files:

I want to rename these files like below:

Basically after .xml I am looking to remove everything.

Here is the code I am trying:

       public static void Main(string[] args)
        {
            DirectoryInfo d = new DirectoryInfo(@"C:\Test\");
            FileInfo[] infos = d.GetFiles();
            
            foreach (FileInfo f in infos)
            {
                var extension = f.FullName.Substring(f.FullName.LastIndexOf('.'), f.FullName.Length - 20);
                
                // Need help here
            } 
        }

Can anybody help me with that?
Thanks

Upvotes: 0

Views: 207

Answers (1)

Prasad Telkikar
Prasad Telkikar

Reputation: 16059

You can Split string by . and Take the first two elements from the split array and Join as a string. You will get the desire file name with an extension.

//I showed you minimal example to solve your problem, update your code accordingly.
var infos = new List<string>(){"Compatible.xml.8790.done", "Compatible.xml.8790.done"};
foreach (var f in infos)
{
   var newFileName = string.Join(".",  f.Split('.').Take(2)); 
   Console.WriteLine(newFileName);     
} 

Try Online

Upvotes: 2

Related Questions