Aytaç Macit
Aytaç Macit

Reputation: 23

IO Exception was unhandled. The process cannot access the file because it is being used

I wrote a program, code seems working but it is not working. It gives IO exception was unhandled error. Some guys say me , you should delete something because program try to use same file at the same time. Please help me!!

      namespace App1508
     {
       public partial class Form2 : Form
      { 

      string goodDir = "C:\\GOOD\\";
      string badDir = "C:\\BAD\\";
      string fromDir = "C:\\DENEME\\";
      List<Image> images = null;
      int index = -1;
      FileInfo[] finfos = null;

       public Form2()
      {
          InitializeComponent();
          DirectoryInfo di = new DirectoryInfo(@"C:\DENEME");
          finfos = di.GetFiles("*.jpg",SearchOption.TopDirectoryOnly);
          images = new List<Image>();
          foreach (FileInfo fi in finfos)
         {
             images.Add(Image.FromFile(fi.FullName));

         }

       }

        private void button1_Click(object sender, EventArgs e)
       {

         finfos[index].MoveTo(Path.Combine("C:\\GOOD", finfos[index].Name));

       }

         private void pictureBox1_Click(object sender, EventArgs e)
       {
        index++;
        if (index < 0 || index >= images.Count)
        index = 0;
        pictureBox1.Image = images[index];

        }

         private void button2_Click(object sender, EventArgs e)
        {
           finfos[index].MoveTo(Path.Combine("C:\\BAD", finfos[index].Name));

         }
        }
       }

Upvotes: 2

Views: 235

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500505

This is the problem:

foreach (FileInfo fi in finfos)
{
    images.Add(Image.FromFile(fi.FullName));
}

Image.FromFile will open a file handle, and won't close it until you dispose of the image. You're trying to move the file without disposing of the image which has that file open first.

I suspect if you dispose of the relevant image in your button1_Click and button2_Click methods (being aware that if it's showing in the PictureBox you'll need to remove it from there first) you'll find it works.

Ref: http://support.microsoft.com/?id=814675

Upvotes: 4

Related Questions