mohad
mohad

Reputation: 31

How to rename files in unknown directory using c#

I want to rename a file with particular extension present inside a folder. For example C:\Users\Username\Desktop\Convert is the file location I'm in. There be another folder for example "C:\Users\Username\Desktop\Convert\Unknown folder". I wont be knowing the name of this unknown folder. There will be a .txt file inside that unknown folder. So how will I access the unknown folder and change the extension of the .txt file to .jpg ?

This is what i have tried and its not working :

string ourPath = @"C:\Users\username\Desktop\Convert\123.txt";
    string newPath = Path.ChangeExtension(ourPath, "jpg");
    File.Move(ourPath, newPath);
}

Upvotes: 0

Views: 211

Answers (1)

Selman Genç
Selman Genç

Reputation: 101731

Get all the files in descendant folders using SearchOption.AllDirectories then find your file and do whatever you want:

var files = Diretory.GetFiles(
          @"C:\Users\Username\Desktop\Convert",
          "*.txt",
          SearchOption.AllDirectories);

var filePath = files.FirstOrDefault(f => Path.GetFileName(f) == "123.txt");

if(filePath != null)
{ 
    // manipulate the file ext. etc..
}

Upvotes: 2

Related Questions