简体   繁体   中英

How to change 2 types of file extensions on one button click in c#?

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.

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"));
}

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"));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM