Avatar of Marina K
Marina K
 asked on

how can i unlock a picture file that was loaded in a picturebox in visual c#?

I am developing a mini game in which the user must recognize the person's face and type in that person's name. Each picture is "saved" in a folder with the person's name, so the game uses both the picture and the filename... This is my code :

using System;
using System.Threading;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;


namespace FaceNameGame
{
    public partial class LevelOnePartTwo : Form
    {
        int point = 0, buttoncount = 0, i=0, h=3, hbuttoncount=0;
        public LevelOnePartTwo()
        {
            InitializeComponent();
        }

        private void LevelOnePartTwo_Load(object sender, EventArgs e)
        {

            string[] files = Directory.GetFiles(@"C:\Users\Marina\Desktop\FaceNameGame\images\Level1\used", "*.jpg", SearchOption.AllDirectories);
            PhotoPicBx.Load(files[i]);
            NameTxtBx.Focus();
            Pointlbl.Text = point.ToString();
            

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void PhotoPicBx_Click(object sender, EventArgs e)
        {

        }

        private void TemplatePicBx_Click(object sender, EventArgs e)
        {

        }

        private void Hintbtn_Click(object sender, EventArgs e)
        {
            hbuttoncount++;
            h--;
            string nameused21 = PhotoPicBx.ImageLocation.ToString();
            string nameused22 = nameused21.Substring(nameused21.LastIndexOf("\\"));
            string nameused23 = nameused22.Remove(nameused22.Length - 4, 4);
            string nameused24 = nameused23.Remove(0, 1);
            string nameused2h = nameused24.Remove(nameused24.Length - h, h);
            NameTxtBx.Text = nameused2h;
            
            if (point > 0 && h>=0)
            {
                point = point - 5;
                Pointlbl.Text = point.ToString();
            }

            if (h <= -1)
            {
                h = 0;
            }

            if (hbuttoncount == 3)
            {
                Hintbtn.Hide();
            }
        }

        int s = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            s++;
            int m = s / 60;
            int h = m / 60;
            Timelbl.Text = "" + h.ToString() + " : " + m.ToString() + " : " + s.ToString();
        }

        private void Checkbtn_Click(object sender, EventArgs e)
        {

            string nameused1 = PhotoPicBx.ImageLocation.ToString();
            string nameused2 = nameused1.Substring(nameused1.LastIndexOf("\\"));
            string nameused3 = nameused2.Remove(nameused2.Length - 4, 4);
            string nameused = nameused3.Remove(0, 1);

            int comp = NameTxtBx.Text.CompareTo(nameused);


            if (comp == 0)
            {
                point = point + 50;
                Pointlbl.Text = point.ToString();
                NameTxtBx.Text = "";
                buttoncount++;




                if (buttoncount <= 2)
                {
                    if (i < 2)
                    {
                        i++;
                        string[] files = Directory.GetFiles(@"C:\Users\Marina\Desktop\FaceNameGame\images\Level1\used", "*.jpg", SearchOption.AllDirectories);
                        PhotoPicBx.Load(files[i]);
                        NameTxtBx.Focus();
                        h = 3;
                        hbuttoncount = 0;
                        Hintbtn.Show();

                    }

                }
            }

            int pointcount = Int32.Parse(Pointlbl.Text);


            if (buttoncount > 2)
            {

                SqlConnection sqlConnection1 = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Marina\\Desktop\\FaceNameGame\\facenamegame\\mygamedb.mdf;Integrated Security=True;Connect Timeout=30");
                System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
                cmd.CommandType = System.Data.CommandType.Text;
                DateTime time = DateTime.Now;              // Use current time
                cmd.CommandText = "insert into Userrecords (Username, Points, Logindate,Level) values(@Username, @Points, @Time, 'Level 1')";
                cmd.Connection = sqlConnection1;





                {


                    cmd.Parameters.AddWithValue("@Username",LoginInfo.UserID );
                    cmd.Parameters.AddWithValue("@Points", pointcount);
                    cmd.Parameters.AddWithValue("@Time", time);
                   
                



                    sqlConnection1.Open();
                    cmd.ExecuteNonQuery();
                    sqlConnection1.Close();
                   
                }


                if (pointcount >= 130)
                {
                    LevelOneSuccessScreen lvlonesucscreen = new LevelOneSuccessScreen();
                    lvlonesucscreen.Show();
                    this.Close();
                }

              if (pointcount < 130)
                {
                    LevelOneRepeatScreen lvlonerepscreen = new LevelOneRepeatScreen();
                    lvlonerepscreen.Show();
                    this.Close();
                   
                }
        }
        }



    }
}

Open in new window

The problem is that this form redirects to the first form that must delete the whole folder of pictures and creates a new one (with the same name but with different photos, when the player must repeat the level)...but Visual Studio always throws an exception that the last picture is used by another process and  can't be deleted...Can i fix this in a way that i can still use the picture with its filename (i mean each photo must be shown with its name underneath)?
C#Game ProgrammingVisual Basic ClassicVisual Basic.NET

Avatar of undefined
Last Comment
louisfr

8/22/2022 - Mon
Dmitry G

I'm not sure how to fix. But obviously if a file (image) is used by a picture box, e.g., you can't delete it. And you can't really do anything about it.

So what would be a possible way to solve the problem?
1. Unload the image, may be load some "temp" picture while you are creating a new folder with different images. And as soon as your images become unlocked - delete current folder and create a new one.

2. Use two folders with different names interchangeably:
you have a folder A with images for your controls,
create a folder B with new images,
reload images to controls
clear the A folder
then repeate in the same order but starting from B...
louisfr

If you use the ImageLocation property instead of the Load method, the file should not be locked.
ASKER CERTIFIED SOLUTION
Ark

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
louisfr

Ark's comment explains why the author has the problem. Mine explains how to solve it.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck