Search code examples
c#winformstimerpicturebox

How to fix The process cannot access the file because it is being used by another process


I wrote a small code to make a slideshow program on a different screen. Everything is running fine also the delete and copy part, unless I do it right after the first picture is shown. If I do it later the debugger steps in.

private void timer1_Tick(object sender, EventArgs e)
{
    string[] images = Directory.GetFiles(@"D:\reflexscherm\root\Logo-teams2", "*.*");
    counter++;
    var maxcount = images.Count();
    textBox1.Text = maxcount.ToString();

    if (counter > maxcount - 1)
    {
        counter = 0;
        maxcount = images.Count();
    }

    //pb1.Image.Dispose();

    pb1.Image = Image.FromFile(images[counter]);
    //Image oldImage = pb1.Image;
    //pb1.Image.Dispose();
    //oldImage.Dispose();
    //pb1.Image = Image.FromFile(images[counter]);
}

private void button2_Click(object sender, EventArgs e)
{ 
    timer1.Stop();
    Image oldImage = pb1.Image; 
    pb1.Image = Image.FromFile(@"D:\reflexscherm\root\sponsor1\x. Groot-logo-REFLEX.jpg");
    pb1.Image.Dispose();
    oldImage.Dispose();

    string[] files = System.IO.Directory.GetFiles(sourcepath);
    string[] delfiles = Directory.GetFiles(targetpath);
    this.Hide();


    foreach (string d in delfiles)
    {
        Image oldI = pb1.Image;
        pb1.Image = Image.FromFile(@"D:\reflexscherm\root\sponsor1\x. Groot-logo-REFLEX.jpg");
        //pb1.Image.Dispose();
        oldI.Dispose();
        File.Delete(d);
    }
    foreach (string s in files)
    {
        string fname = s.Substring(sourcepath.Length + 1);
        File.Copy(Path.Combine(sourcepath, fname), Path.Combine(targetpath, fname), true);
        this.Show();
        timer1.Start();
    }

What I am looking for is some help to adjust the code, so when I change files in sourcefolder then program copies the files from the sourcefolder to the targetfolder. I know how to use filewatcher. I am using a button to test the code.


Solution

  • You should use a readonly File Access if you don't want it to be locked:

    using( FileStream stream = new FileStream( path, FileMode.Open, FileAccess.Read ) )
    
    {
    
         image = Image.FromStream( stream );
    
    }
    

    Hope it helps...