Move files in C#

MKS picture MKS · Nov 29, 2012 · Viewed 62.2k times · Source

I am moving some images (filenames are(1).PNG, (2).PNG and so on) from one directory to another. I am using the following code:

for (int i = 1; i < n; i++)
{
    try
    {
        from = "E:\\vid\\(" + i + ").PNG";
        to = "E:\\ConvertedFiles\\" + i + ".png";
        File.Move(from, to); // Try to move
        Console.WriteLine("Moved"); // Success
    }
    catch (IOException ex)
    {
        Console.WriteLine(ex); // Write error
    }
}

However, I am getting the following error:

A first chance exception of type System.IO.FileNotFoundException occurred in mscorlib.dll

System.IO.FileNotFoundException: Could not find file 'E:\vid\(1).PNG'.

Also, I am planning to rename the files so that the converted file name will be 00001.png, 00002.png, ... 00101.png and so on.

Answer

Tobia Zambon picture Tobia Zambon · Nov 29, 2012

I suggest you to use '@' in order to escape slashes in a more readable way. Use also Path.Combine(...) in order to concatenate paths and PadLeft in order to have your filenames as your specifics.

for (int i = 1; i < n; i++)
{
    try
    {
        from = System.IO.Path.Combine(@"E:\vid\","(" + i.ToString() + ").PNG");
        to = System.IO.Path.Combine(@"E:\ConvertedFiles\",i.ToString().PadLeft(6,'0') + ".png");

        File.Move(from, to); // Try to move
        Console.WriteLine("Moved"); // Success
    }
    catch (IOException ex)
    {
        Console.WriteLine(ex); // Write error
    }
}