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

  • (2 Pages)
  • +
  • 1
  • 2

26 Replies - 4611 Views - Last Post: 02 December 2013 - 01:00 PM Rate Topic: -----

#16 vinay.kalled@gmail.com  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 15-November 13

Re: The process cannot access the file because it is being used by another

Posted 02 December 2013 - 08:52 AM

View Postjhouns, on 02 December 2013 - 08:43 AM, said:

Can you please post it in code tags?


I dont know about code tags, so could u please tell how to post it in code tags?
Was This Post Helpful? 0
  • +
  • -

#17 jhouns  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 25
  • View blog
  • Posts: 100
  • Joined: 21-December 09

Re: The process cannot access the file because it is being used by another

Posted 02 December 2013 - 09:12 AM

In the editor type:
[ code ]Your code goes here[ /code ]

Without the spaces in between '[', ']' and 'code'.

This post has been edited by jhouns: 02 December 2013 - 09:13 AM

Was This Post Helpful? 0
  • +
  • -

#18 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3529
  • View blog
  • Posts: 10,931
  • Joined: 05-May 12

Re: The process cannot access the file because it is being used by another

Posted 02 December 2013 - 09:18 AM

View Postvinay.kalled@gmail.com, on 02 December 2013 - 10:42 AM, said:

Actually in my form there are 5 buttons, for Browse, Save, Previous, Next, Back.
As i load the form, the picturebox is loaded with images & i can iterate through them & wen i click back button i wil be directed to home form & when i again come back to same page its showing error: process cannot be access file becz its been used by other process

:
        private void Next_Click(object sender, EventArgs e)
        {
            //check next position image is have or not       
            if (i + 1 < filecount)          
            {               
                pictureBox1.Image = Image.FromFile(alist[i + 1].ToString());   
                i = i + 1;           
            }
        }

        private void Previous_Click(object sender, EventArgs e)
        {

            //check previous position image is have or not          
            if (i - 1 >= 0)           
            {                
                pictureBox1.Image = Image.FromFile(alist[i - 1].ToString());    
                i = i - 1;         
            }

        }



And there lies your problem. To quote from MSDN documentation for Image.FromFile():

Quote

The file remains locked until the Image is disposed.

Was This Post Helpful? 3
  • +
  • -

#19 modi123_1  Icon User is offline

  • Suitor #2
  • member icon



Reputation: 9044
  • View blog
  • Posts: 33,951
  • Joined: 12-June 08

Re: The process cannot access the file because it is being used by another

Posted 02 December 2013 - 09:19 AM

View Postvinay.kalled@gmail.com, on 02 December 2013 - 09:52 AM, said:

View Postjhouns, on 02 December 2013 - 08:43 AM, said:

Can you please post it in code tags?


I dont know about code tags, so could u please tell how to post it in code tags?

Highlight your text that is code and click the button (in the editor) that says [ CODE ].
Was This Post Helpful? 0
  • +
  • -

#20 jhouns  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 25
  • View blog
  • Posts: 100
  • Joined: 21-December 09

Re: The process cannot access the file because it is being used by another

Posted 02 December 2013 - 09:22 AM

Great catch Skydiver! I looked at the MSDN for that function and completely missed it, I was obsessed with looking for a stream, how stupid of me!
Was This Post Helpful? 0
  • +
  • -

#21 vinay.kalled@gmail.com  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 15-November 13

Re: The process cannot access the file because it is being used by another

Posted 02 December 2013 - 09:56 AM

View Postjhouns, on 02 December 2013 - 09:12 AM, said:

In the editor type:
[ code ]Your code goes here[ /code ]

Without the spaces in between '[', ']' and 'code'.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Collections;
using System.IO;

namespace InventoryManagement
{
    public partial class Catalogue : Form
    {
         SqlConnection con = new SqlConnection("Data Source=VINAYAK-PC;Initial Catalog=Inventor Management;Integrated Security=True");
        SqlCommand cmd = new SqlCommand();

        ArrayList alist = new ArrayList();
        DataTable dt = new DataTable(); 
        SqlDataAdapter da = new SqlDataAdapter(); 
        int filecount = 0;
        int i = 0;
        int filelength = 0;

        public Catalogue()
        {
            InitializeComponent();
        }

        private void Catalogue_Load(object sender, EventArgs e)
        {
            //try
            //{

                string tmppath = Path.GetDirectoryName(Application.ExecutablePath) + "\\tmpdir";
                if (!System.IO.Directory.Exists(tmppath))
                {
                    System.IO.Directory.CreateDirectory(tmppath);
                }



                //Convert bytes into image and store in temperory path           
                con.Open();
                cmd = new SqlCommand("select * from Photo", con); //change table name as per your record            
                da = new SqlDataAdapter(cmd);
                dt = new DataTable();
                da.Fill(dt);
                con.Close();
                Byte[] byt;
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i <= dt.Rows.Count - 1; i++)
                    {
                        //tmppath.DefaultIfEmpty();

                         byt = (Byte[])dt.Rows[i]["Picture_Details"]; //change here your field name instead of cntnt               
                        

                        System.IO.File.WriteAllBytes(tmppath + "\\" + i + ".jpg", byt);
                        //System.IO.File.Delete(byt.ToString());
                        //byt.DefaultIfEmpty();
                        byt = null;
                
                    }
                    
                    
                    
                    //Specify Source folder path here               
                    LoadImage(tmppath);
                    //Directory.Delete(tmppath);
                    //System.IO.Directory.Delete(tmppath);
                    
                    
                    
                    

                }
                
            //}

            //catch (Exception m)
            //{
            //    MessageBox.Show(m.ToString());
            //}
        }


        //Load images from temp directory to picture box         
        void LoadImage(string path)   
        {            
            System.IO.DirectoryInfo inputDir = new System.IO.DirectoryInfo(path);           
            try          
            {
                if ((inputDir.Exists))   
                {
                    //Get Each jpg files from a source folder and stored in the arraylist
                    System.IO.FileInfo file = null;   
                    foreach (System.IO.FileInfo eachfile in inputDir.GetFiles())         
                    {
                        file = eachfile;                      
                        if (file.Extension.ToLower() == ".jpg")      
                        {                           
                            alist.Add(file.FullName);     
                            //Store file count here        
                            filecount = filecount + 1;                    
                        }
                        
                    }
                    //Initally show first image in the picture box          
                    pictureBox1.Image = Image.FromFile(alist[0].ToString());              
                    i = 0;
                    
                    
                   
                }
            
                
            }
            catch (Exception ex)   
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void Catalogue_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void Next_Click(object sender, EventArgs e)
        {
            //check next position image is have or not       
            if (i + 1 < filecount)          
            {               
                pictureBox1.Image = Image.FromFile(alist[i + 1].ToString());   
                i = i + 1;           
            }
        }

        private void Previous_Click(object sender, EventArgs e)
        {

            //check previous position image is have or not          
            if (i - 1 >= 0)           
            {                
                pictureBox1.Image = Image.FromFile(alist[i - 1].ToString());    
                i = i - 1;         
            }

        }

        string picLoc = "";

        private void Browse_Click(object sender, EventArgs e)
        {

            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                dlg.Filter = "JPG Files(*.jpg)|*.jpg|GIF Files(*.gif)|*.gif|All Files(*.*)|*.*";
                dlg.Title = "Select Photo Picture.";
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    picLoc = dlg.FileName.ToString();
                    pictureBox1.ImageLocation = picLoc;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void Insert_Click(object sender, EventArgs e)
        {

             try
             {
                 byte[] img = null;
                 //FileStream f = new FileStream();
                 FileStream fs = new FileStream(picLoc, FileMode.Open, FileAccess.Read);
                 BinaryReader br = new BinaryReader(fs);
                 img = br.ReadBytes((int)fs.Length);
                 // string sql = "INSERT INTO Photo(Picture_ID,Description,Picture_Deatils) VALUES(" + textBoxEID.Text + ",'" + textBoxFirstName.Text + "', '" + textBoxLastName.Text + "',@IMG)";
                 string sql = "INSERT INTO Photo(Picture_Details) VALUES (@Picture_Details)";

                 if (con.State != ConnectionState.Open)
                     con.Open();
                 cmd = new SqlCommand(sql, con);
                 cmd.Parameters.Add(new SqlParameter("@Picture_Details", img));
                 //cmd.Parameters.Add(new SqlParameter("@Description", textBox1.Text));
                 int x = cmd.ExecuteNonQuery();
                 MessageBox.Show(x.ToString() + " records saved.");
                 con.Close();
                 textBox1.Text = "";
                 //pictureBox1.Image = null;
                 this.Refresh();
                 fs.Close();
                 br.Close();
             }
             catch (Exception ex)
             {
                 con.Close();
                 MessageBox.Show(ex.Message);
             }

        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            this.Refresh();
        }

        private void Back_Click(object sender, EventArgs e)
        {

            this.Hide();
            Home h = new Home();
            h.Show();
            
        }
}



Was This Post Helpful? 0
  • +
  • -

#22 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4448
  • View blog
  • Posts: 7,744
  • Joined: 08-June 10

Re: The process cannot access the file because it is being used by another

Posted 02 December 2013 - 10:13 AM

View Postjhouns, on 02 December 2013 - 10:22 AM, said:

Great catch Skydiver! I looked at the MSDN for that function and completely missed it, I was obsessed with looking for a stream, how stupid of me!


It's an easy one to miss if you haven't encountered it before. In fact, I wouldn't even know about that if it weren't for tlhIn`toq mentioning it in several threads that I've seen.

The "safe" way to handle it is to read the file into a MemoryStream and use Image.FromStream instead. Roundabout way to do the same thing, but doesn't leave an open file handle (assuming you clean up after yourself when you read it in).
Was This Post Helpful? 0
  • +
  • -

#23 vinay.kalled@gmail.com  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 13
  • Joined: 15-November 13

Re: The process cannot access the file because it is being used by another

Posted 02 December 2013 - 10:27 AM

View PostCurtis Rutland, on 02 December 2013 - 10:13 AM, said:

View Postjhouns, on 02 December 2013 - 10:22 AM, said:

Great catch Skydiver! I looked at the MSDN for that function and completely missed it, I was obsessed with looking for a stream, how stupid of me!


It's an easy one to miss if you haven't encountered it before. In fact, I wouldn't even know about that if it weren't for tlhIn`toq mentioning it in several threads that I've seen.

The "safe" way to handle it is to read the file into a MemoryStream and use Image.FromStream instead. Roundabout way to do the same thing, but doesn't leave an open file handle (assuming you clean up after yourself when you read it in).


Can u please tell what all changes i should make in my code, becz m not getting what exactly to do
Was This Post Helpful? 0
  • +
  • -

#24 Michael26  Icon User is offline

  • DIC-head, major DIC-head
  • member icon

Reputation: 353
  • View blog
  • Posts: 1,513
  • Joined: 08-April 09

Re: The process cannot access the file because it is being used by another

Posted 02 December 2013 - 12:34 PM

I see one other potential problem, you are using ArrayList which is leftover practice from first .net framework. ArrayList only store objects and that could lead to casting issues, i recommend using Generic list, List<T> where T will stand for, in your case, FileInfo that way you will only store FileInfo type instead of objects. Also there is the boxing and unboxing issue both computationally expensive processes.
Was This Post Helpful? 0
  • +
  • -

#25 Curtis Rutland  Icon User is online

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4448
  • View blog
  • Posts: 7,744
  • Joined: 08-June 10

Re: The process cannot access the file because it is being used by another

Posted 02 December 2013 - 12:42 PM

None of that is really his problem (although it should be corrected, no doubt). The problem is because Image.FromFile leaves the file handle open under certain circumstances. He needs to look up MemoryStream and Image.FromStream and use them instead of Image.FromFile. But I'm not going to provide the actual code, because that's just not how we do things here.
Was This Post Helpful? 0
  • +
  • -

#26 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3529
  • View blog
  • Posts: 10,931
  • Joined: 05-May 12

Re: The process cannot access the file because it is being used by another

Posted 02 December 2013 - 12:44 PM

View Postvinay.kalled@gmail.com, on 02 December 2013 - 12:27 PM, said:

View PostCurtis Rutland, on 02 December 2013 - 10:13 AM, said:

The "safe" way to handle it is to read the file into a MemoryStream and use Image.FromStream instead.


Can u please tell what all changes i should make in my code, becz m not getting what exactly to do


He did. If you take a few seconds in MSDN to look up the documentation for those things that Curtis mentioned, it should be pretty self evident. If not, post your new code and tell us what you do not understand.
Was This Post Helpful? 0
  • +
  • -

#27 Michael26  Icon User is offline

  • DIC-head, major DIC-head
  • member icon

Reputation: 353
  • View blog
  • Posts: 1,513
  • Joined: 08-April 09

Re: The process cannot access the file because it is being used by another

Posted 02 December 2013 - 01:00 PM

Quote

Can u please tell what all changes i should make in my code, becz m not getting what exactly to do

You need to do 2 things
first load file into Memory stream and secondly use the Image.FromStream to make image from that stream. I think that is sufficient help for you.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2