Link to home
Start Free TrialLog in
Avatar of r3nder
r3nderFlag for United States of America

asked on

image being used by another process

I have a process for pulling an image from the database when I use it once it pulls fine if I close the form in the app and open it again I ge tthe same error

any ideas
        private void ShowImage(int ID)
        {
            int @id = ID;
            string conString = ConfigurationManager.ConnectionStrings["connection"].ToString();
            SqlConnection conn = new SqlConnection(conString);
            SqlDataAdapter da = new SqlDataAdapter("spx_MsgUploadFiles_Pull", conn);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.SelectCommand.Parameters.AddWithValue("@id", id);
            DataSet ds = new DataSet("read");
            conn.Open();
            da.Fill(ds, "read");
            conn.Close();
            //storing the file in byte array 
            byte[] MyData = new byte[0];
            DataRow myRow;
            myRow = ds.Tables["read"].Rows[0];
            MyData = (byte[])myRow["Document_File"];
            
            string name = myRow["filename"].ToString();
            int ArraySize = new int();
            ArraySize = MyData.GetUpperBound(0);
            if (ArraySize > -1)
            {

                string temp = ConfigurationManager.AppSettings["AppfileLogRootPath"];
                string path = temp + name;
                File.WriteAllBytes(path, MyData);
                byte[] pdf = (byte[])myRow["Document_File"];
                Image image = Image.FromFile(path);
                pbImage.Image = image;
            }

        }

Open in new window

Avatar of r3nder
r3nder
Flag of United States of America image

ASKER

exact error
The process cannot access the file '\\server\Users\Logs\newuser\openfiles\image.jpg' because it is being used by another process.
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Or you can try something and dispose it off correctly.

      public partial class Form1 : Form
      {
          private Image _image;

            public Form1()
            {
                  InitializeComponent();
                _image = Image.FromFile(@"c:\temp\image.jpg");
                pictureBox1.Image = _image;
            }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_image != null)
            {
                _image.Dispose();
            }
        }
      }
Just use your own code to show the image, just that while closing the form, you explicitly call the Dispose() method on the image instance. This way your code is doing all the clean up before it closes.

Arun
Avatar of r3nder

ASKER

as always Idle, you are the Batman of the code world :o)