IOException: The process cannot access the file 'filename' because it is being used by another process

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. 

0
multiplex7777
3/22/2007 10:17:15 AM
asp.net.getting-started 91979 articles. 4 followers. Follow

8 Replies
1947 Views

Similar Articles

[PageSpeed] 28
Get it on Google Play
Get it on Apple App Store

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"
0
MorningZ
3/22/2007 11:12:26 AM

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);
    }
    // ...
}
0
OesisAcc2
3/22/2007 11:16:39 AM

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().
 

0
multiplex7777
3/22/2007 3:05:40 PM
multiplex7777:

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"
0
MorningZ
3/22/2007 7:53:59 PM

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 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:
1    //Upload a new photo
2    protected void btnUpload_Click(object sender, EventArgs e)
3 {
4 string sTempName, AppearOrder1, thumbnailName;
5 bool fileExtensionOK = false;
6 7 if (FileUpload1.HasFile)
8 {
9 //Check if file extension is ok 10 String fileExtension = Path.GetExtension(FileUpload1.FileName).ToLower();
11 String[] allowedExtensions = { ".gif", ".jpg" };
12 for (int i = 0; i < allowedExtensions.Length; i++)
13 {
14 if (fileExtension == allowedExtensions[i])
15 {
16 fileExtensionOK = true;
17 }
18 }
19 20 if (fileExtensionOK)
21 {
22 try 23 {
24 sTempName = path + FileUpload1.FileName;
25 FileUpload1.PostedFile.SaveAs(sTempName); //Exception occurs here
26 //lblMsg.Text += "<br />Received " + FileUpload1.FileName + " ContentType=" + FileUpload1.PostedFile.ContentType + " Length=" + FileUpload1.PostedFile.ContentLength + "<br />"; 27 28 if (Convert.ToInt32(FileUpload1.PostedFile.ContentLength) > maxFileSize)
29 {
30 //File size too big 31 File.Delete(sTempName);
32 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."; 33 }
34 else
35 {
36 Bitmap bmpImage_sm = this.CreateThumbnail(sTempName, 124, 124);
37 thumbnailName = Path.GetFileNameWithoutExtension(FileUpload1.FileName) + "
_sm" + fileExtension;
38 bmpImage_sm.Save(path + thumbnailName);
39 40 //Save record in database table: Check if there is a previous photo with the same filename.
41 //If so, just update the Caption and AppearOrder instead of creating a new record.
42 strQuery = "
SELECT * FROM Photos WHERE UserID = '" + UserID + "' AND Filename = '" + FileUpload1.FileName + "'";
43 using (SqlConnection cn = new SqlConnection(Utility.strCon))
44 {
45 cn.Open();
46 SqlCommand cm = new SqlCommand(strQuery, cn);
47 SqlDataReader rd = cm.ExecuteReader();
48 AppearOrder1 = AppearOrder.Text;
49 if (Utility.IsNull(AppearOrder.Text) || !Utility.IsInteger(AppearOrder.Text) || AppearOrder.Text == "")
50 AppearOrder1 = "
0";
51 else
52 AppearOrder1 = AppearOrder.Text;
53 54 if (rd.Read())
55 {
56 strQuery = "
UPDATE Photos SET Caption = " + Utility.strProc(Caption.Text) + ", AppearOrder = '" + AppearOrder1 + "', " +
57 "
IsAvatar = 0, LastUpdatedBy = '" + UserID + "', LastUpdated = GetDate() " +
58 "
WHERE PhotoID = '" + rd["PhotoID"].ToString() + "'";
59 Utility.MyExecuteNonQuery(strQuery);
60 }
61 else
62 {
63 strQuery = "
INSERT INTO Photos (UserID, Filename, Filename_sm, Caption, AppearOrder, IsAvatar, LastUpdatedBy, LastUpdated) " +
64 "
VALUES ('" + UserID + "', '" + FileUpload1.FileName + "', '" + thumbnailName + "', " + Utility.strProc(Caption.Text) + ", '" +
65 AppearOrder1 + "'
, 0, '" +
66 UserID + "'
, GetDate() )";
67 Utility.MyExecuteNonQuery(strQuery);
68 }
69 70 //Set ProfileTable LastUpdatedBy and LastUpdated so that this user appears under "Latest updates" 71 strQuery = "
UPDATE ProfileTable " +
72 "
SET LastUpdatedBy = '" + UserID + "', LastUpdatedDate = GetDate() " +
73 "
WHERE UserID = '" + UserID + "'";
74 Utility.MyExecuteNonQuery(strQuery);
75 }
76 77 //lblMsg.Text = "Your photo has been uploaded. Choose another photo to upload, or click 'Cancel' to view all your photos.";
78 //Return to photos page
79 Response.Redirect("
~/Photos.aspx?id=" + UserID, false);
80 }
81 }
82 catch (Exception ex)
83 {
84 lblMsg.Text = "
The image could not be uploaded. Please ensure that your file is an image file.";
85 }
86 }
87 else
88 {
89 lblMsg.Text = "
Only .jpg and .gif files allowed.";
90 }
91 }
92 else
93 {
94 lblMsg.Text = "
No file selected.";
95 }
96 }
 
Thanks for your help! 
0
multiplex7777
3/23/2007 2:43:12 AM
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"
0
MorningZ
3/23/2007 1:48:42 PM

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.
0
multiplex7777
3/26/2007 1:39:37 AM

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");


RAGHAV

MVP ASP/ASP.Net Read My Blog


MARK THE POST AS ANSWER IF IT HELPS U.


"Success doesn't come to you…you go to it."--Marva Collins




"Success does not come to those who wait . . . and it does not wait for anyone to come to it." Anonymous


0
raghav_khunger
11/26/2008 11:12:33 AM
Reply:

Similar Artilces:

Cannot copy assembly 'DotNetNuke' to file '<assemly>'. The process cannot access the file because it is being used by another process.
I am in the process of creating a new module and I keep running into this problem. This happens every time I try to build the project. SOMETIMES I can get it working again by deleting the previously generated assemblies and reopening the project, but that doesn't always work and I'd like for the problem not to be there in the first place. My new module project is located at \DotNetNuke\DesktopModules\NewModule The build path for the assembly is set to ..\..\bin which is \DotNetNuke\Bin I am also using a project reference rather than an assembly reference so that shouldn't be the p...

(urgent) The process cannot access the file '[filename]' because it is being used by another process.
For some reason my users are getting the following error in production: "System.IO.IOException: The process cannot access the file 'D:\[omitted]\TestingCenter\Xml\TestPlans\dbeckett\20071204_4' because it is being used by another process." This is occurring in my production environment, but did not occur in development or staging environments. Here is my code:string path = ConfigurationManager.AppSettings["xmlPath"];_modules = new Modules(); ClearLineItems();if (Directory.Exists(path + CurrentUser.Username)) { path += CurrentUser.Username + "\\";...

The process cannot access the file '.....' because it's being used by another process
In VB6.0 I was using API calls for checking that a process has finished and then continue with other steps:       var_process_number = Shell("wzunzip.exe -o " & """" & fld_ZIP_file_name & """" & " " & """" & fld_import_path & """", vbMinimizedNoFocus)       'wait until the uncompressing is over         var_process_handle = OpenProcess(&H100000, True, var_process_number)         WaitForSingleObject var_process_handle, -1         CloseHandle var_process_handle In ASP....

System.IO.IOException: The process cannot access the file '' because it is being used by another process.
I am getting the above mentioned error. My code is as below and the stack trace also follows. I am not trying to open the file or copy or move, i just want to attach it to an email. Dim _today As Date Dim _dayNumber As Integer Dim _wcDayNumber As Integer Dim _stepDownVal As Integer Dim _negated As Integer Dim _wcDay As Date Dim wc As String Dim _filename As String Dim _foldername As String _today = Date.Today _dayNumber = Date.Today.DayOfWeek _wcDayNumber = 1 _stepDown...

Could not write to output file '...\obj\Debug\abc.dll" -- 'The process cannot access the file because it is being used by another process'
I use VS2003. Recently I keep getting this error when building the solution. Any idea how to fix it?? THANKS!  Could not write to output file '...\obj\Debug\abc.dll" -- 'The process cannot access the file because it is being used by another process' Close any other projects that link to this dll (i.e., any extra Visual Studio instances).  Also, try closing the app-- If you are running/debugging the project that references this dll, then you may be using that dll.  ---------------------------------------MCP - Web Based Client Development .NET 2.0 Thanks f...

System.IO.IOException: The process cannot access the file 'xxxx.pdf' because it is being used by another process.
I have a basic vb.net form that collects some data, allows users to add attachments, and when they click submit, generates an email that includes the data and the attachments that were uploaded to the server. To keep my server clean, after the email is sent, I want to remove the attachments... However, I keep getting an error that says it can't access the file because it is being used by another process.  I can either send the email or delete the file, but can't get the two to work together... Any suggestions? my code behind...        Protected S...

PLease help getting error as The process cannot access the file 'D:\Inventracksys\Inventorytracking Vendorwisereport_1.emf' because it is being used by another process
Dear All, I am making web application using Asp.net C#(Visual Studio2005). And Sql server 2005 as a back End  I generated local mode report but as there was no printing option available . I assign printing feature to button click by exporting the data to EMF format and print Now when I run it through IDE VS2005 then it does not show any error. But when I run in through IIS in intranet it showing me this error   The process cannot access the file 'D:\Inventracksys\Inventorytracking Vendorwisereport_1.emf' because it is being used by another process Where I am going wrong pl...

The process cannot access the file '' because it is being used by another process.
 Hai guys..Write now i am designing an event calendar . I am having an error message while trying to delete an event with images.. The event detail page is view with event details and the image under the event (i.e) photogallery is shown. while i am trying to delete the event with image it show an error message like "The process cannot access the file '<filepathname>' because it is being used by another process." . I have listed my code here.. 1 protected void gvAdminEventDetail_RowDeleting(object sender, GridViewDeleteEventArgs e) 2 { 3 ...

PLease help getting error as The process cannot access the file 'D:\Inventracksys\Inventorytracking Vendorwisereport_1.emf' because it is being used by another process #2
Dear All, I am making web application using Asp.net C#(Visual Studio2005). And Sql server 2005 as a back End  I generated local mode report but as there was no printing option available . I assign printing feature to button click by exporting the data to EMF format and print Now when I run it through IDE VS2005 then it does not show any error. But when I run in through IIS in intranet it showing me this error   The process cannot access the file 'D:\Inventracksys\Inventorytracking Vendorwisereport_1.emf' because it is being used by another process Where I am going wrong pl...

SqlBulkCopy & problem: The process cannot access the file '' because it is being used by another process.
I use the SQLBulkCopy class to insert data from a excel file to SQL Server table.             Dim OleDbConn As OleDbConnection = New OleDbConnection(sExcelConnectionString)            Dim OleDbCmd As OleDbCommand = New OleDbCommand(("SELECT * FROM " & sWorkbook), OleDbConn)            OleDbConn.Open()            Dim dr As OleDbDataReader = OleDbCmd.ExecuteReade...

Can not access file 'filename' because it is being used by another process
I'm getting the following error on my web servers occassionally and the site is inaccessible until I reboot. It only happens occassionally and I can't force the duplication of it. The file is one of the DLLs that the app is trying to access. Is anyone familiar with this? Server Error in '/' Application. -------------------------------------------------------------------------------- Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify you...

(VB) The process cannot access the file 'C:something/something.jpg' because it is being used by another process.
I found articles about this error but none mentioned the situation where the very first action the code takes (or so I believe) shuts down the program as if something else had previously happened to tie up the file. The code below is very short, two controls on the ASPX page and only two lines of code behind.  The first one causes the error: PictureUploadControl.SaveAs(Server.MapPath("~/images/ORIGINAL") & PictureUploadControl.FileName) Please find, if possible, in the code below what error is causing a denial of file access.  Thank you for your help. The an...

Process can't access file because it is being used by another process
Hi I've to extract a zip file and delete that zip file. When i extract zip file, the file is extracted successfully, but when i try to delete the file, it throws the Exception "Process can't access file because it is being used by another process". Can some one solve my problem. Thanks in advance.ZIA UR REHMAN how are you extracting the file? if you're using a library, remember to close the zipfile before you try deleting it. yeah this was the problems... thanks alot for the help. i really appreciate. ThaksZIA UR REHMAN...

! Unable to write to output file 'C:\Documents and Settings\Administrator\VSWebCache\ELEAD\DotNetNuke\obj\Debug\DotNetNuke.dll': The process cannot access the file because it is being used by another
I have trouble with DotNetNuke version 3.0.11 I put folder DotNetNuke in C:\Inetpub\wwwroot When I build its solution, I usually get this error: " Unable to write to output file 'C:\Documents and Settings\Administrator\VSWebCache\ELEAD\DotNetNuke\obj\Debug\DotNetNuke.dll': The process cannot access the file because it is being used by another process. Unable to write to output file 'C:\Documents and Settings\Administrator\VSWebCache\ELEAD\DotNetNuke\obj\Debug\DotNetNuke.pdb': Access is denied.  " I can't repair it. If I want to continue, I must close all solution, and delete fold...

Web resources about - IOException: The process cannot access the file 'filename' because it is being used by another process - asp.net.getting-started

Resources last updated: 11/28/2015 11:03:02 PM