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

  • (2 Pages)
  • +
  • 1
  • 2

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

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

  • New D.I.C Head

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

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

Posted 01 December 2013 - 10:07 AM

private void Catalogue_Load(object sender, EventArgs e)
        {

                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);
                da = new SqlDataAdapter(cmd);
                dt = new DataTable();
                da.Fill(dt);
                con.Close();
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i <= dt.Rows.Count - 1; i++)
                    {
                        //tmppath.DefaultIfEmpty();
                        Byte[] byt = (Byte[])dt.Rows[i]["Picture_Details"];     
                        System.IO.File.WriteAllBytes(tmppath + "\\" + i + ".jpg", byt);
                        byt = null;     
                    }                   
                    
                    //Specify Source folder path here               
                    LoadImage(tmppath);

                }
                
        }


        //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());
            }
        }

I am getting error @ this line: System.IO.File.WriteAllBytes(tmppath + "\\" + i + ".jpg", byt);
Error: The process cannot access the file because it is being used by another.

This post has been edited by andrewsw: 01 December 2013 - 10:15 AM
Reason for edit:: Please use code tags


Is This A Good Question/Topic? 0
  • +

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

#2 astonecipher  Icon User is offline

  • Major DIC Head
  • member icon

Reputation: 726
  • View blog
  • Posts: 3,167
  • Joined: 03-December 12

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

Posted 01 December 2013 - 10:27 AM

That means the file is opened by either you or the system still and it cannot change it while it is still open. Is the file open while you are running the program?
Was This Post Helpful? 0
  • +
  • -

#3 andrewsw  Icon User is offline

  • It's just been revoked!
  • member icon

Reputation: 3611
  • View blog
  • Posts: 12,419
  • Joined: 12-December 12

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

Posted 01 December 2013 - 10:36 AM

It might be worth re-booting the computer as well.
Was This Post Helpful? 0
  • +
  • -

#4 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 01 December 2013 - 10:44 AM

View Postastonecipher, on 01 December 2013 - 10:27 AM, said:

That means the file is opened by either you or the system still and it cannot change it while it is still open. Is the file open while you are running the program?


No its not opened anywhere.
Was This Post Helpful? 0
  • +
  • -

#5 Michael26  Icon User is offline

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

Reputation: 362
  • View blog
  • Posts: 1,534
  • Joined: 08-April 09

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

Posted 01 December 2013 - 11:24 AM

It's not simple as that there is no certain way to check if the file is in use because even millisecond after you do the check file may not be in use or vice versa.
That loop looks suspicious to me, don't you have to close the writing stream after you are done? If you are looping you need to write then close so you can write again in next iteration.

Correct me if i'm wrong. I think that is why you are getting that error.
Was This Post Helpful? 0
  • +
  • -

#6 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 01 December 2013 - 01:02 PM

I know File.Create opens a stream that needs to be closed. Does Directory.CreateDirectory do the same? Could be the source of the issue here.

Edit:
As mentioned above. .Close might need to be called after write all bytes to close the stream.

This post has been edited by jhouns: 01 December 2013 - 01:03 PM

Was This Post Helpful? 0
  • +
  • -

#7 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 - 02:55 AM

View PostMichael26, on 01 December 2013 - 11:24 AM, said:

It's not simple as that there is no certain way to check if the file is in use because even millisecond after you do the check file may not be in use or vice versa.
That loop looks suspicious to me, don't you have to close the writing stream after you are done? If you are looping you need to write then close so you can write again in next iteration.

Correct me if i'm wrong. I think that is why you are getting that error.


Ya it might be the exception but m unable to close File or FileStream becz File.Close() & FileStream.Close() is not available, so could u please tell me how to close it.

View Postjhouns, on 01 December 2013 - 01:02 PM, said:

I know File.Create opens a stream that needs to be closed. Does Directory.CreateDirectory do the same? Could be the source of the issue here.

Edit:
As mentioned above. .Close might need to be called after write all bytes to close the stream.



Directory.CreateDirectory creates just a directory n need not be closed it. I don think so this is the issue.
Might be the FileStream exception but m unable to close File or FileStream becz File.Close() & FileStream.Close() is not available, so could u please tell me how to close it.
Was This Post Helpful? 0
  • +
  • -

#8 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 - 03:38 AM

Having checked the docs, MSDN state that it doesn't leave an open stream and so you should be okay. CreateDirectory isn't causing the issue. Similarly WriteAllBytes closes the file behind it (MSDN: '...writes the contents of the byte array to the file, and then closes the file.'), so while the error is on that line, it's not what's locking the file.

For a start. Make this:
if (!System.IO.Directory.Exists("tmppath"))



This:
if (!System.IO.Directory.Exists(tmppath))



Then tell me how it goes.
Was This Post Helpful? 0
  • +
  • -

#9 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 - 06:55 AM

View Postjhouns, on 02 December 2013 - 03:38 AM, said:

Having checked the docs, MSDN state that it doesn't leave an open stream and so you should be okay. CreateDirectory isn't causing the issue. Similarly WriteAllBytes closes the file behind it (MSDN: '...writes the contents of the byte array to the file, and then closes the file.'), so while the error is on that line, it's not what's locking the file.

For a start. Make this:
if (!System.IO.Directory.Exists("tmppath"))



This:
if (!System.IO.Directory.Exists(tmppath))



Then tell me how it goes.


Its showing same error
Was This Post Helpful? 0
  • +
  • -

#10 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 - 07:02 AM

Okay, do any of the files already exist in that temp directory? If so, delete the directory then re-run the application.

Also if you put a break point at the start of the for loop and step through it, does it error on the first iteration or second+?
Was This Post Helpful? 0
  • +
  • -

#11 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3620
  • View blog
  • Posts: 11,276
  • Joined: 05-May 12

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

Posted 02 December 2013 - 07:02 AM

What antivirus software are you using? Have you tried telling it to skip doing scans on your temporary path? (Some AV software are slow and tend to leave files locked while they are doing their scans.)
Was This Post Helpful? 0
  • +
  • -

#12 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 - 07:25 AM

View Postjhouns, on 02 December 2013 - 07:02 AM, said:

Okay, do any of the files already exist in that temp directory? If so, delete the directory then re-run the application.

Also if you put a break point at the start of the for loop and step through it, does it error on the first iteration or second+?


It shows error on 2nd iteration & after the loop if i make tmppath null its shows error as temppath should not be null

View PostSkydiver, on 02 December 2013 - 07:02 AM, said:

What antivirus software are you using? Have you tried telling it to skip doing scans on your temporary path? (Some AV software are slow and tend to leave files locked while they are doing their scans.)


M using Avast antivirus n how to disable scanning of tmppath in avast antivirus??
Was This Post Helpful? 0
  • +
  • -

#13 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 - 07:33 AM

Okay, so we know that somewhere in the first iteration something isn't changing/being closed properly. As for the 'temppath' thing, I didn't mean set the path to nothing, I meant delete the folder on disk manually through windows explorer, this was just to ensure that it wasn't having problems with the files existing in the first place (although it shouldn't be an issue). At the moment I'm having a hard time figuring out from your code what the issue is. Please ensure you have tried Skydiver's idea.

EDIT: For avast, just right clicking the icon and temporarily disabling shields for 10 minutes should do.

This post has been edited by jhouns: 02 December 2013 - 07:34 AM

Was This Post Helpful? 0
  • +
  • -

#14 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:42 AM

View Postjhouns, on 02 December 2013 - 07:33 AM, said:

Okay, so we know that somewhere in the first iteration something isn't changing/being closed properly. As for the 'temppath' thing, I didn't mean set the path to nothing, I meant delete the folder on disk manually through windows explorer, this was just to ensure that it wasn't having problems with the files existing in the first place (although it shouldn't be an issue). At the moment I'm having a hard time figuring out from your code what the issue is. Please ensure you have tried Skydiver's idea.

EDIT: For avast, just right clicking the icon and temporarily disabling shields for 10 minutes should do.


Ya i tried with disabling avast antivirus but result is same.

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
My whole code is here u can check it:

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();
            
        }


This post has been edited by Skydiver: 02 December 2013 - 09:14 AM
Reason for edit:: Put code in code tags. Learn to do this yourself.

Was This Post Helpful? 0
  • +
  • -

#15 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 - 08:43 AM

Can you please post it in code tags?
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2