It works fine on my local machine, but once I upload it to my remote server, I
sometimes (about 1 in 8 times) hit this exception:
System.IO.IOException: The process cannot access the file 'C:\Inetpub\vhosts\myfile.jpg' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at System.Web.HttpPostedFile.SaveAs(String filename)
at Webform.btnUpload_Click(Object sender, EventArgs e) in c:\inetpub\vhosts\users\httpdocs\demo\UploadPhoto.aspx.cs:line 116
Again, works fine on localhost, but on my remote server, I sometimes get this error:
System.IO.IOException: The process cannot access the file 'C:\Inetpub\vhosts\myfiletodelete.jpg' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.Delete(String path)
at About.lnkDelete_Click(Object sender, CommandEventArgs e) in c:\inetpub\vhosts\users\Photos.aspx.cs:line 220
I read this is something to do with not closing the filestream, or using a Dispose method. However, I really don't know how to apply it to my code. Can someone help me please?
Can't tell you exactly where or when the exception happens, but i can tell you the reason for it is because you do not properly ".Dispose()" of some objects (using Drawing.Image or .Bitmap?)
"If you make it idiot proof, they'll build a better idiot"
You don't have to close the Stream when using the File Upload. That's done automatically. Further more, an open stream will always throw this exception.
I am not sure why this exception occures, but I guess that some other process (website call) is using the image in the very same moment. Is the filename the same every time you upload? Is the image used on a website with heavy traffic? Is a Backup-thread
running on the remote computer that is backuping this folder? Are you doing something else with this images somewhere else?
For now: lock your IO operations and try again. (see example)
Matthias - thanks. I did as you indicated, but the same error is still occuring.
MorningZ - How do I invoke the .Dispose() method on my image and where do I invoke it? I'm sorry I've been searching all over the web for an answer. I keep seeing advice that I need to do a Dispose but I really don't know
where to do the Dispose().
Matthias - thanks. I did as you indicated, but the same error is still occuring.
MorningZ - How do I invoke the .Dispose() method on my image and where do I invoke it? I'm sorry I've been searching all over the web for an answer. I keep seeing advice that I need to do a Dispose but I really don't know
where to do the Dispose().
it'd be easier if i just saw your code (if it's too big to post, you can send it to me via email, which is myusername @ gmail.com)... but here's a super simple example
Dim img As Drawing.Image = Drawing.Image.FromStream(PostedFile.InputSteam)
' Do stuff with image
img.Dispose() <-- releases the lock on the file
The code the guy posted above would never work as it's not the delete that has/needs the lock on the file, it's the creation of the file
"If you make it idiot proof, they'll build a better idiot"
Marked as answer by multiplex7777 on Mar 26, 2007 01:39 AM
Here's my code for the File.Delete. I have bolded the lines where the IOException occurs in both instances.
As you can see, there is nowhere where I have assigned anything to a Drawing.Image, so I don't know where I could call the .Dispose() method to release the lock on the file.
protected void lnkDelete_Click(object sender, CommandEventArgs e)
{
string relativepath, path, sTempName;
//set relative path to this user's image directory
relativepath = "~/Images/Users/" + FriendID + "/";
path = Server.MapPath(relativepath);
PhotoID = e.CommandArgument.ToString();
try
{
//Get the photo and thumbnail filenames
strQuery = "SELECT * " +
"FROM Photos WHERE PhotoID = '" + PhotoID + "'";
using (SqlConnection cn = new SqlConnection(Utility.strCon))
{
cn.Open();
SqlCommand cm = new SqlCommand(strQuery, cn);
SqlDataReader rd = cm.ExecuteReader();
if (rd.Read())
{
if (File.Exists(path + rd["Filename"].ToString()))
{
sTempName = path + rd["Filename"].ToString();
File.Delete(sTempName); //Exception occurs here
}
if (File.Exists(path + rd["Filename_sm"].ToString())) { sTempName = path + rd["Filename_sm"].ToString(); File.Delete(sTempName); //Exception occurs here }
} } strQuery = "DELETE FROM Photos WHERE PhotoID = '" + PhotoID + "'"; Utility.MyExecuteNonQuery(strQuery);
GetSelectCommand(); Response.Redirect("~/Photos.aspx?id=" + FriendID; //Prevents subsequent refreshing of page from deleting extra photos
}
catch (Exception ex) { lblMsg.Text = "Sorry, that file can't be deleted now. Please try again later. The issue is currently being looked into."; } }
Could it be the File.Exists method that is causing the problems?
Here's my code for the FileUpload:
//Upload a new photoprotected void btnUpload_Click(object sender, EventArgs e) { string sTempName, AppearOrder1, thumbnailName; bool fileExtensionOK = false; if (FileUpload1.HasFile) { //Check if file extension is ok
String fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower(); String[] allowedExtensions = { ".gif", ".jpg" }; for (int i = 0; i < allowedExtensions.Length; i++) { if (fileExtension == allowedExtensions[i]) { fileExtensionOK = true; } } if (fileExtensionOK) { try
{ sTempName = path + FileUpload1.FileName; FileUpload1.PostedFile.SaveAs(sTempName); //Exception occurs here //lblMsg.Text += "<br />Received " + FileUpload1.FileName + " ContentType=" + FileUpload1.PostedFile.ContentType + " Length=" + FileUpload1.PostedFile.ContentLength + "<br />";if (Convert.ToInt32(FileUpload1.PostedFile.ContentLength) > maxFileSize) { //File size too big
File.Delete(sTempName); lblMsg.Text += "Your file size is too large! Please use an <a href='http://www.gimp.org/' target='_new'><u>image editor</u></a> to resize your photo before uploading it.";
} else { Bitmap bmpImage_sm = this.CreateThumbnail(sTempName, 124, 124); thumbnailName = Path.GetFileNameWithoutExtension(FileUpload1.FileName) + "_sm" + fileExtension; bmpImage_sm.Save(path + thumbnailName); //Save record in database table: Check if there is a previous photo with the same filename. //If so, just update the Caption and AppearOrder instead of creating a new record.
strQuery = "SELECT * FROM Photos WHERE UserID = '" + UserID + "' AND Filename = '" + FileUpload1.FileName + "'"; using (SqlConnection cn = new SqlConnection(Utility.strCon)) { cn.Open(); SqlCommand cm = new SqlCommand(strQuery, cn); SqlDataReader rd = cm.ExecuteReader(); AppearOrder1 = AppearOrder.Text; if (Utility.IsNull(AppearOrder.Text) || !Utility.IsInteger(AppearOrder.Text) || AppearOrder.Text == "") AppearOrder1 = "0"; else AppearOrder1 = AppearOrder.Text;
if (rd.Read()) { strQuery = "UPDATE Photos SET Caption = " + Utility.strProc(Caption.Text) + ", AppearOrder = '" + AppearOrder1 + "', " + "IsAvatar = 0, LastUpdatedBy = '" + UserID + "', LastUpdated = GetDate() " + "WHERE PhotoID = '" + rd["PhotoID"].ToString() + "'"; Utility.MyExecuteNonQuery(strQuery); } else { strQuery = "INSERT INTO Photos (UserID, Filename, Filename_sm, Caption, AppearOrder, IsAvatar, LastUpdatedBy, LastUpdated) " + "VALUES ('" + UserID + "', '" + FileUpload1.FileName + "', '" + thumbnailName + "', " + Utility.strProc(Caption.Text) + ", '" + AppearOrder1 + "', 0, '" + UserID + "', GetDate() )"; Utility.MyExecuteNonQuery(strQuery); } //Set ProfileTable LastUpdatedBy and LastUpdated so that this user appears under "Latest updates"
strQuery = "UPDATE ProfileTable " + "SET LastUpdatedBy = '" + UserID + "', LastUpdatedDate = GetDate() " + "WHERE UserID = '" + UserID + "'"; Utility.MyExecuteNonQuery(strQuery); } //lblMsg.Text = "Your photo has been uploaded. Choose another photo to upload, or click 'Cancel' to view all your photos."; //Return to photos page
Response.Redirect("~/Photos.aspx?id=" + UserID, false); } } catch (Exception ex) { lblMsg.Text = "The image could not be uploaded. Please ensure that your file is an image file."; } } else { lblMsg.Text = "Only .jpg and .gif files allowed."; } } else { lblMsg.Text = "No file selected."; } }
as i mentioned above, it's not the delete that is the problem, it's where the file gets created on the file system..... that's the code that is broken,
not the code above
"If you make it idiot proof, they'll build a better idiot"
You're absolutely right! I realised I did create a bitmap at line 36 of my second chunk of code. I have since added a bmpImage_sm.Dispose() method after my bmpImage_sm.Save method, and it seems to work fine now. Thanks for your help! Really appreciate
it.
SmtpClient smtpClient =
new SmtpClient();MailMessage objMail =
new MailMessage();MailAddress objMail_toaddress =
new MailAddress("ToAddress");MailAddress objMail_fromaddress =
new MailAddress("FromAddress");
Best practise in such scenarios (file handling) is to put the code where you access the file in your applications inside of "using" statements to ensure such resources are released to the system.
// C-Sharp
try
{
using (StreamReader reader = new StreamReader(@"C:\file.txt"))
{
// do some reading
reader.Close();
}
}
catch (IOException) // Should capture access exception
{
// Show error; do nothing; etc.
}
Click "Mark as Answer" on the post that helped you to help future readers.
multiplex777...
Member
554 Points
273 Posts
IOException: The process cannot access the file 'filename' because it is being used by another pr...
Mar 22, 2007 10:17 AM|LINK
Hi everyone,
I'm having some difficulty with my File upload and File delete processes.
For the Upload, I do like:
sTempName = path + FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(sTempName); //sTempName = C:\Inetpub\vhosts\myfile.jpg
It works fine on my local machine, but once I upload it to my remote server, I sometimes (about 1 in 8 times) hit this exception:
System.IO.IOException: The process cannot access the file 'C:\Inetpub\vhosts\myfile.jpg' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at System.Web.HttpPostedFile.SaveAs(String filename)
at Webform.btnUpload_Click(Object sender, EventArgs e) in c:\inetpub\vhosts\users\httpdocs\demo\UploadPhoto.aspx.cs:line 116
Similarly for my Delete, I do:
sTempName = path + rd["Filename"].ToString(); //sTempName = C:\Inetpub\vhosts\myfiletodelete.jpg
if (File.Exists(sTempName))
{
File.Delete(sTempName); //line 220
}
Again, works fine on localhost, but on my remote server, I sometimes get this error:
System.IO.IOException: The process cannot access the file 'C:\Inetpub\vhosts\myfiletodelete.jpg' because it is being used by another process.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.Delete(String path)
at About.lnkDelete_Click(Object sender, CommandEventArgs e) in c:\inetpub\vhosts\users\Photos.aspx.cs:line 220
I read this is something to do with not closing the filestream, or using a Dispose method. However, I really don't know how to apply it to my code. Can someone help me please?
Thanks.
MorningZ
Star
8849 Points
1822 Posts
Re: IOException: The process cannot access the file 'filename' because it is being used by anothe...
Mar 22, 2007 11:12 AM|LINK
OesisAcc2
Member
274 Points
70 Posts
Re: IOException: The process cannot access the file 'filename' because it is being used by anothe...
Mar 22, 2007 11:16 AM|LINK
Hi,
You don't have to close the Stream when using the File Upload. That's done automatically. Further more, an open stream will always throw this exception.
I am not sure why this exception occures, but I guess that some other process (website call) is using the image in the very same moment. Is the filename the same every time you upload? Is the image used on a website with heavy traffic? Is a Backup-thread running on the remote computer that is backuping this folder? Are you doing something else with this images somewhere else?
For now: lock your IO operations and try again. (see example)
Cheers,
Matthias :)
Example:
private static object _lock = new object(); // some code... protected void btnUploadClick(object sender, EventArgs e) { // ... lock (_lock) { FileUpload1.PostedFile.SaveAs(sTempName); } // ... } protected void btnDeleteClick(object sender, EventArgs e) { // ... lock (_lock) { File.Delete(sTempName); } // ... }multiplex777...
Member
554 Points
273 Posts
Re: IOException: The process cannot access the file 'filename' because it is being used by anothe...
Mar 22, 2007 03:05 PM|LINK
Matthias - thanks. I did as you indicated, but the same error is still occuring.
MorningZ - How do I invoke the .Dispose() method on my image and where do I invoke it? I'm sorry I've been searching all over the web for an answer. I keep seeing advice that I need to do a Dispose but I really don't know where to do the Dispose().
MorningZ
Star
8849 Points
1822 Posts
Re: IOException: The process cannot access the file 'filename' because it is being used by anothe...
Mar 22, 2007 07:53 PM|LINK
it'd be easier if i just saw your code (if it's too big to post, you can send it to me via email, which is myusername @ gmail.com)... but here's a super simple example
Dim img As Drawing.Image = Drawing.Image.FromStream(PostedFile.InputSteam)
' Do stuff with image
img.Dispose() <-- releases the lock on the file
The code the guy posted above would never work as it's not the delete that has/needs the lock on the file, it's the creation of the file
multiplex777...
Member
554 Points
273 Posts
Re: IOException: The process cannot access the file 'filename' because it is being used by anothe...
Mar 23, 2007 02:43 AM|LINK
MorningZ,
Here's my code for the File.Delete. I have bolded the lines where the IOException occurs in both instances. As you can see, there is nowhere where I have assigned anything to a Drawing.Image, so I don't know where I could call the .Dispose() method to release the lock on the file.
protected void lnkDelete_Click(object sender, CommandEventArgs e) { string relativepath, path, sTempName; //set relative path to this user's image directory relativepath = "~/Images/Users/" + FriendID + "/"; path = Server.MapPath(relativepath); PhotoID = e.CommandArgument.ToString(); try { //Get the photo and thumbnail filenames strQuery = "SELECT * " + "FROM Photos WHERE PhotoID = '" + PhotoID + "'"; using (SqlConnection cn = new SqlConnection(Utility.strCon)) { cn.Open(); SqlCommand cm = new SqlCommand(strQuery, cn); SqlDataReader rd = cm.ExecuteReader(); if (rd.Read()) { if (File.Exists(path + rd["Filename"].ToString())) { sTempName = path + rd["Filename"].ToString(); File.Delete(sTempName); //Exception occurs hereMorningZ
Star
8849 Points
1822 Posts
Re: IOException: The process cannot access the file 'filename' because it is being used by anothe...
Mar 23, 2007 01:48 PM|LINK
multiplex777...
Member
554 Points
273 Posts
Re: IOException: The process cannot access the file 'filename' because it is being used by anothe...
Mar 26, 2007 01:39 AM|LINK
MorningZ,
You're absolutely right! I realised I did create a bitmap at line 36 of my second chunk of code. I have since added a bmpImage_sm.Dispose() method after my bmpImage_sm.Save method, and it seems to work fine now. Thanks for your help! Really appreciate it.raghav_khung...
All-Star
32835 Points
5563 Posts
MVP
Re: IOException: The process cannot access the file 'filename' because it is being used by anothe...
Nov 26, 2008 10:12 AM|LINK
Hi,
I was Also Facing Same Kind Of Problem
I am Writing The code which i found Successuful transaction
I have The code of sending Attchment with Mail.
Create A Temp Folder in th root directory of ur application
At the End I had Release The Lock So that File Can Be Deleted.
Try This
string name = txtName.Value.ToString(); string Address = txtAddress.Value.ToString(); string ContactNo = txtContactNo.Value.ToString(); //string txtMobileNo = Request["txtMobileNo"].ToString(); string Email = txtEmail.Value.ToString();string jobTitle = txtJobTitle.Value.ToString();
SmtpClient smtpClient = new SmtpClient(); MailMessage objMail = new MailMessage(); MailAddress objMail_toaddress = new MailAddress("ToAddress"); MailAddress objMail_fromaddress = new MailAddress("FromAddress");objMail.From = objMail_fromaddress;
objMail.To.Add(objMail_toaddress);
objMail.Subject = "Job Seeker Resume";
StringBuilder strbuld = new StringBuilder();strbuld.Append(".........");
objMail.Body =
Convert.ToString(strbuld);
string strdir = Server.MapPath("Temp\\");string strfilename = Path.GetFileName(inputResume.PostedFile.FileName);inputResume.PostedFile.SaveAs(strdir + strfilename);
Attachment At = new Attachment(strdir + strfilename);objMail.Attachments.Add(At);
objMail.IsBodyHtml = true;smtpClient.Host =
"YourHostName"; smtpClient.Credentials = new System.Net.NetworkCredential("YourUserName", "YourPassword"); try{
smtpClient.Send(objMail);
}
catch (Exception ex){
}
objMail.Dispose();
File.Delete(strdir + strfilename);Response.Redirect(
"Jobs_Res_Thanks.htm");sudhanva
Member
276 Points
124 Posts
Re: IOException: The process cannot access the file 'filename' because it is being used by anothe...
May 13, 2010 09:33 AM|LINK
Best practise in such scenarios (file handling) is to put the code where you access the file in your applications inside of "using" statements to ensure such resources are released to the system.
// C-Sharp try { using (StreamReader reader = new StreamReader(@"C:\file.txt")) { // do some reading reader.Close(); } } catch (IOException) // Should capture access exception { // Show error; do nothing; etc. }