Click here to Skip to main content
15,868,306 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello!!

i am taking photographs of the user and then saving them . every time user clicks his photograph is taken and then it gets saved inside Images folder. now the user can take as many photographs as he likes but each photograph for a particular user replaces the previous one if taken for that user so i always have only 1 photograph for 1 user. now sometimes it says file is in use. what should i do ??

here is the code.

void CreatePhoto()
    {
        try
        {
            filename = getPassNo() + "-"+ DateTime.Now.Year.ToString();

            if( File.Exists(Server.MapPath("Images/" + filename)))
            {
                
                File.Delete(Server.MapPath("Images/" + filename));
  
            }
            string strPhoto = Request.Form["imageData"]; //Get the image from flash file
            byte[] photo = Convert.FromBase64String(strPhoto);
            FileStream fs = new FileStream(Server.MapPath("Images/" + filename), FileMode.OpenOrCreate, FileAccess.Write);
            
            BinaryWriter br = new BinaryWriter(fs);
            
            br.Write(photo);
           
            br.Flush();
          
            br.Close();
           
            fs.Close();
            string x = "Update Image Set Taken =1";
            Dal.ExnonQry(x);
         

        }
        catch (Exception Ex)
        {

        }
        finally
        {
           
            Response.Redirect("Default.aspx?FN=" + filename + "");
        }
    }
Posted
Comments
thatraja 21-Nov-13 2:20am    
what's the complete error message?
ujjwal uniyal 21-Nov-13 2:50am    
File in use. this error doesn't come regularly .
Er Daljeet Singh 21-Nov-13 2:41am    
you are getting this because when you try to delete file at that time it is open or in processing.if you are using then web application then why don't you use fileupload control for saving images.

1 solution

This problem comes with the File.Delete, File.Copy File.Move methods: they return immediately, just after the OS has been told what to do. But the OS may require a little more time to perform the action on the disk. Hence you could check if the file still exists (and wait if necessary) before you write the next file.
By the way, I'd prefer to save the new photo to a temporary file, and then move it to its final location: if osmething goes wrong with creating the photo on the server, you could still keep the old image there.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900