Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Monday, March 25, 2013

A generic error occurred in GDI+

This is a common exception you'll get when trying to delete or rename an image file. The problem is that the method to load the image from file will put a lock on the file, so you can't do anything with it until you dispose the image.
There are two ways around that: either load the image from a stream or dispose the image before deleting or renaming the file.
Loading the image from stream works, but the actual loading is a bit slower and you need to keep the stream open until you don't need the image anymore. You can't just load it with a stream, close it, and then work with the image. It might work with some file format, but the documentation itself tells you to keep the stream open. Here's how to do it:
using (FileStream stream = new FileStream(@"path\to\image", FileMode.Open, FileAccess.Read))
{
    pictureBox1.Image = Image.FromStream(stream);
}
The problem here is that after assigning the image to the picturebox the stream will close ("using" statement). You could do this instead:
FileStream stream = new FileStream(@"path\to\image", FileMode.Open, FileAccess.Read);
pictureBox1.Image = Image.FromStream(stream);
But then you'll have an open stream forever, until you close it, which is not really a good solution. The real solution comes from loading the image from file, like this:
pictureBox1.Image = Image.FromFile(@"path\to\image");
And then dispose it correctly.
I'm sure you know that we should always dispose everything disposable after we're done with it, so it shouldn't be a surprise, but the problem in disposing and then deleting or renaming soon after is that the image has not enough time to be disposed. So, if you do this:
pictureBox1.Image.Dipose();
File.Delete(@"path\to\image");
You'll most likely incur in the "A generic error occurred in GDI+" exception, because the lock on the file is not yet released.
The REAL and FINAL solution to this, is to call the garbage collector before deleting the file.
You can do that by writing this:
GC.Collect();
After disposing the image.
There's still a problem though, the Collect() method is called asynchronously, that means you could and probably will incur in the same error as before, since the file could still be locked. You need to tell the program to wait for the garbage collector to finish, by adding this:
GC.WaitForPendingFinalizers();
After the GC.Collect().
So, the final code would be:
pictureBox1.Image.Dipose();
GC.Collect();
GC.WaitForPendingFinalizers();
File.Delete(@"path\to\image");
And that's how you delete or rename an image file safely in C#.

Saturday, March 23, 2013

Batch rename with leading zeroes

Let's say you're writing a batch rename function in C#, but you want the number in the filenames to have a leading zero, like this:
filename-01
filename-02
filename-03
etc. etc.

You need to find how many zeroes you need to add, based on the number of the total files, or you would end up with something like this:
filename-09
filename-010
filename-011
etc. etc.
Which looks bad, and it could give problems with some programs depending on how they sort a file list.
The result you want is one where the number's count is the same, indipendently from the number of files, even if you have a million files, it needs to work.
Doing an if/else is bad, because you would need to know the number of files before-hand. The solution is pretty simple, this is the result you will get:

filename-08
filename-09
filename-10
filename-11

Or, using larger numbers:

filename-0001
filename-0002
...
filename-0099
filename-0100
...
filename-0999
filename-1000
etc. etc. 
Let's see the code:

List<string> files = new List<string>(); //Our list of files

//populate the file list in any way you want, like this
private void populateFiles() 
{
    string dir = @"path\to\your\directory";
    foreach(string s in Directory.GetFiles(dir)) 
    {
        files.Add(s);
    }
    //Or you could do a files.AddRange(Directory.GetFiles(dir));
}

private void batchRename() 
{
    //Cycle every file in the list
    for (int i = 0; i < files.Count; i++)
    {
        //zeroesAmount contains the number of zeroes to add to the title
        //Let's say the files.Count is 758 and "i" is now at 19
        //We get the length of the string "758", which is 3
        //We get the length of the string "19", which is 2
        //We subtract them, 3 - 2 = 1, so it's 1 zero to add
        int zeroesAmount = files.Count.ToString().Length - i.ToString().Length;

        //This is the string that will be added to the file name
        string zeroes = "";

        //Actual cycle to add the zeroes number to the string
        for (int ii = 0; ii < zeroesAmount; ii++)
        {
            zeroes += "0";
        }

        //Assigning the new file name and renaming, with the File.Move function
        string parent = Directory.GetParent(files[i]);
        string fileName = Path.GetFileNameWithoutExtension(files[i]);
        string extension = Path.GetExtension(files[i]);
        string newFile = parent + "\\" + fileName + "-" + zeroes + i.ToString() + extension;
        if (!File.Exists(newFile))
        {
            File.Move(files[i], newFile);
        }
    }
}

prettyprint