Reputation: 47
I would like to change more file extensions at the same time, for example change all .txt files to .txt.NO and .jpg.NO to .jpg
My code looks like this:
private void button_Click(object sender, EventArgs e)
{
DirectoryInfo d = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
FileInfo[] infos = d.GetFiles();
foreach (FileInfo f in infos)
{
File.Move(f.FullName, f.FullName.ToString().Replace(".txt", ".txt.NO"));
File.Move(f.FullName, f.FullName.ToString().Replace(".jpg.NO", ".jpg"));
}
}
I get and error when I try to do 2 changes at once. When I was using only the first File.Move
line alone my program was working.
Upvotes: 1
Views: 88
Reputation: 6155
The problem is that you are moving/renaming the same file two times and in your second Move
the property f.FullName
is still the one with the .txt
extension but this file does not exist anymore because you moved it already.
You should use a condition to check if it's a textfile or an image.
Something like this for example
foreach (FileInfo f in infos)
{
if (f.FullName.EndsWith(".txt"))
{
File.Move(f.FullName, f.FullName.ToString().Replace(".txt", ".txt.NO"));
}
else if (f.FullName.EndsWith(".jpg.NO"))
{
File.Move(f.FullName, f.FullName.ToString().Replace(".jpg.NO", ".jpg"));
}
}
Upvotes: 2
Reputation: 30022
When you rename the file in the first line, the second would fail because the file no longer has that name.
You need a condition based on the file extension.
foreach (FileInfo f in infos)
{
if(f.FullName.EndsWith(".txt"))
File.Move(f.FullName, f.FullName.ToString().Replace(".txt", ".txt.NO"));
else if(f.FullName.EndsWith(".jpg.NO"))
File.Move(f.FullName, f.FullName.ToString().Replace(".jpg.NO", ".jpg"));
}
Upvotes: 5