Click here to Skip to main content
15,909,539 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear All,

I want to remove the extension from all the available files in all the sub folders in a Main folder.

Example : Below is the folder structure.

MainDirectory
|
|---> SubDirectory1/ abc1.config.txt / abc2.config.txt /  abc3.config.txt /
|
|---> SubDirectory2/ abc1.config.txt / abc2.config.txt /  abc3.config.txt /
|
|---> SubDirectory3/ abc1.config.txt / abc2.config.txt /  abc3.config.txt /

So, I want ".txt" extension to be removed from all the files in all the sub directories programmatically in c#, so that I will be having only config files at the end.

Please suggest or provide some piece of c# code.

Thanks in advance,

What I have tried:

I have tried Path.ChangeExtension which actually replaces the extension with null, but it does not apply for physical file. I mean, it just gives the value to the user in logical way.
Posted
Updated 27-Jul-16 21:47pm
v3
Comments
BillWoodruff 28-Jul-16 3:18am    
Do you need to perform this change recursively ? i.e., are there arbitrary levels of nesting ?

Once you have changed the extension you need to use File.Move Method (String, String) (System.IO)[^] to rename it.
 
Share this answer
 
Try:
C#
string[] files = Directory.GetFiles(@"D:\Temp\", "*.txt", SearchOption.AllDirectories);
foreach (string file in files)
    {
    File.Move(file, file.Substring(0, file.Length - 4));
    }
 
Share this answer
 
Comments
Raj.rcr 28-Jul-16 3:45am    
Working as expected.. Thanks So Much..
OriginalGriff 28-Jul-16 3:49am    
You're welcome!
You can call 'Move on the File, while removing the ".txt" extension, which will result in the extension being ".config:"
C#
string path = @"C:\Users\Whoever\Desktop\SubDirectory1\abc1.txt.config";

string newpath = Path.ChangeExtension(path, "");
File.Move(path, newpath);
While this "works," the need to manipulate file extensions in this way makes me wonder if there isn't a simpler way to do whatever it is you are doing here.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900