Solved

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

Posted on 2016-10-07
4
86 Views
Last Modified: 2016-10-08
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?
0
Comment
Question by:Marina K
  • 2
  • 2
4 Comments
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 41833850
Instead of calling Load, use the Image property, and assign to it the result of reading the bytes of the image into a stream.

e.g.

private void LevelOnePartTwo_Load(object sender, EventArgs e)
{
    string[] files = Directory.GetFiles(@"C:\Users\Marina\Desktop\FaceNameGame\images\Level1\used", "*.jpg", SearchOption.AllDirectories);
    byte[] imageBytes = File.ReadAllBytes(files[i]);
    MemoryStream ms = new MemoryStream(imageBytes);
    Image i = Image.FromStream(ms);
    IDisposable toDispose = PhotoPicBx.Image;

    PhotoPicBx.Image = i;
    
    if (toDispose != null)
    {
      toDispose.Dispose();
    }
    
    NameTxtBx.Focus();
    Pointlbl.Text = point.ToString();
}

Open in new window

1
 

Author Comment

by:Marina K
ID: 41834988
@käµfm³d 👽 Thanks... it is a good solution...but i need to use the filename too, and i do not think that this is a possible thing to do using memorystream.
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 41835181
What do you mean by "use the filename"? You've got it in "files[0]". If you need to save back to the file, then just call the Save method on the Image that assigned to the PictureBox.
1
 

Author Closing Comment

by:Marina K
ID: 41835187
Thank you very much ...it works with sowing the picture...but with the "using the filename" i meant that the filename of each picture must be shown under the picture
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Get id from json Data with NewtonSoft 3 34
SQL syntax in VB.net 5 29
Allow user to hide and show datagridview columns 4 17
SQL Exceptions 3 37
Enums (shorthand for ‘enumerations’) are not often used by programmers but they can be quite valuable when they are.  What are they? An Enum is just a type of variable like a string or an Integer, but in this case one that you create that contains…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now