.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

How to delete a file which was accessed by other process ?

Posted By:      Posted Date: September 06, 2010    Points: 0   Category :.NET Framework
Does Windows have a "unlock object" method in order to delete a file which is being used by another process ? Thanks

View Complete Post

More Related Resource Links

Delete file after associated process ends


I'm not sure this belongs in the BCL, but I can't find a better place. I'm trying to write a snippet that downloads and shows files. The brief process is the following

1. Write the temp file (by StreamWriter, etc, not really important)

2. Open the file with the associated program by shell execute or show the Open As dialog if no program is associated.

var p = new Process();
bool err;
  p.StartInfo = new ProcessStartInfo(fileName);
  err = true;
if( err )
  var psi = new ProcessStartInfo("rundll32.exe");
  psi.UseShellExecute = false;
  psi.Arguments = "shell32.dll,OpenAs_RunDLL \"" + fileName + "\"";
  p.StartInfo = psi;

3. After associated program closes, delete the temp file (this is done by a background proc

Programmatically delete a .webpart file from wpcatalogs folder from an IIS website


We are using a third party wsp in our solution which directly adds the web parts into the web application store rather than the web part gallery(References to them are present in IIS site's wpcatalog directory). We want to remove these web part files so that the users will not be able to add these web parts to pages directly. Or any other modification so that users will not be able to add these directly. Is there a way we can do this programmatically?

Error "The process cannot access the file ....." occurs while using function "ExportToStream"


Dear all,

   I sometimes get the following error while printing crystal report to pdf:

   System.Runtime.InteropServices.COMException (0x80004005): The process cannot access the file because
it is being used by another process. at CrystalDecisions.ReportAppServer.Controllers.ReportSourceClass.Export
(ExportOptions pExportOptions, RequestContext pRequestContext) at CrystalDecisions.ReportSource.EromReportSourceBase.ExportToStream
(ExportRequestContext reqContext) at CrystalDecisions.CrystalReports.Engine.FormatEngine.ExportToStream(ExportRequestContext reqContext)
 at CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportOptions options) at
 CrystalDecisions.CrystalReports.Engine.ReportDocument.ExportToStream(ExportFormatType formatType) at
 CommonWA.CommonFunc.GetPDFMemoryStream(DCMSReportDoc _dcmsreportdoc, Boolean& _DataExist) in E:\wwwroot\ASPWA\CommonWA\CommonCom.vb:line 382

  The error not occurs frequently but sometimes it will happen, can someone tell me why the error occurs and how can I solve the problem?

Thank you very much.


How to delete an image file assigned to a PictureBox xontrol ?

In a Windows form application, some image files are assigned to PictureBox controls. I am trying to delete those image files. The first approach [1] with "Image.FromFile" gives an error message of "Another process is using this image file", although "Image.Dispose()" is executed. The second approach [2] using "Image.FromStream" results (X) images for PictureBoxes and Buttons, if "fs.Close()" is inclided. Without "fs.Close()", it gives the same error message of "Another process is using...". How can I display images properly and delete those images files ? Thanks [1] pictureBoxSelected.Image = Image.FromFile(@actualImage); . . . pictureBoxSelected.Image.Dispose(); pictureBoxSelected.Image = Image.FromFile(@tempImage);                                                if (System.IO.File.Exists(actualImage) == true) {     System.IO.File.Delete(actualImage); } [2] FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); pictureBox.Image = System.Drawing.Image.FromStream(fs); fs.Close();

Restoring 2008 Database with Filestream - Process cannot access file error

I'm trying to restore a copy of a database that has a filestream and am getting the error below. I've tried with move option to specify a new path and left it with default path, neither worked. Did a trace with procmon, didn't see anything. FileStream1 is a new folder that the restore process creates. I've deleted the folder, tried it with a new name, re-took the backup from the source machine, restarted SQL, rebooted the machine, drive permissions are open. I've run out of ideas on how to debug further. Looking up the error online wasn't much help either. Msg 3634, Level 16, State 1, Line 1 The operating system returned the error '32(The process cannot access the file because it is being used by another process.)' while attempting 'OpenFile' on 'X:\Data\FileStream1\4ecb2e48-0eee-4c99-a3f0-f1e6c7f00b24\f2efe374-9481-4c1b-a7f2-dcdcee350807\0000001b-0000aaa6-00f6'. Msg 3013, Level 16, State 1, Line 1 RESTORE DATABASE is terminating abnormally. ' SQL Server 2008 SP 1, MS Server 2008 R2 Server

Log file WSS_AdminService.log - can i delete it?

Hi, I've noticed that the size of a file WSS_AdminService.log every user profile setting eg. in C:\Documents and Settings\Default User\Local Settings\Temp is about 2GB currently. I understand that this file is updated by wssadmin.exe (the Windows SharePoint Services Administration service). questions: 1. we have many users who are no longer using the account to login to the server, can i delete teh file then? 2. is there a way that i can allow only a single file WSS_AdminService.log in a specific user account to be access by wssadmin.exe? in this case we can save more HDD space. because, if we have more than 50 users account, then 50 * 2GB and it's already 100GB. instead of 100GB, can we just make it 2GB and this file is share by all the sharepoint users? thanks. Sam. Does anyone have any insight into how I might alter what is logged or how often, or even just to persuade it to 'housekeep' better, as the file continues to grow (reaching 750MB on the first server I noticed this on)? As far as I can see it is not related to the Diagnostic logging settings in Central Administration > Operations. Renaming the file to append a date on a regular basis is my current solution - a new copy is then created by WSS Admin on its next log cycle.

Import Error: Could not process the file Documents/Application Deployment.mht as a Single File Web P

Hi there everyone, Version: Windows Sharepoint Services 3.0 with Cumulative Update June 29, 2010 applied. I am having issues importing an exported site into a different domain. I've overcome most of the issues and actually got most of the site to import, however, the import process get's stuck on import a Single File Web Page document from a document library. I believe the original cause of this error is http://support.microsoft.com/kb/980079 The issue I face now is, I already have a large number of .mht files in my document library which I do need to import into the test environment (or that I might need to restore in a DR scenario). Does anyone have any information on either: forcing the import commmand to "on error resume next" (ie. not stop processing when it encounters an error) fixing the already corrupt .mht files in the database easily The error text from the import command is: Error: Could not process the file Documents/Application Deployment.mht as a Single File Web Page document. at Microsoft.SharePoint.Library.SPRequest.CreateOrUpdateFileAndItem(String bstrUrl, String bstrWebRelativeUrl, Guid& docId, Object varDoc, Int32 docLength, Int32 exists, String bstrCreatedBy, String bstrModifiedBy, Int32 iCreatedByID, Int32 iModifiedByID, Int32 iVersion, Object varTimeCreated, Object varTimeLastModified, Object varProperties, String checkInComment, Int3

delete a csv file created via StreamWriter?

I don't know if this is the correct forum.. but, is there a way I can automatically delete the following .csv file that was created via streamwriter (after it is viewed by an individual)?CODE (I would like to automatically delete the_filename.csv)://///////////////////////////////////////////////////////////////////////////////////////////////            string filename = "~/downloadfiles/data_complex987654321_filename.csv";             StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath(filename));             StringBuilder sb = new StringBuilder();            string filename = "~/the_filename.csv";            StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath(filename));            StringBuilder sb = new StringBuilder();

can not delete data file after emptying the file

hi, i have two data file groups. data and data_new. i moved all objects from file group data to data_new. i verified not a single object is there in data file group. i want to remove all files in file group data and and evantually filegroup as well. i am trying to delete the file present in this file group. but it is throwing error cant be deleted because file is not empty .any one plz suggest.

How do i force SharePoint to open file automatically during check out process?

Currently, when checking out a file (doc., excel, pdf etc.) in Sharepoint, i right click on doc. and click "check out". Then a window pops up and saying " you are about to check out:...." and i choose the option of saving the file in my Local Drafts Folder. The issue is that the file does not open automatically once i click "ok" in pop up window. I have go back to file in SharePoint and click on it again to open it. How do i force SharePoint to automatically open the file, when i go through the check it out process? Thank you all for your feedback.

delete file from server

hello champs...i want to delete the folders present in server...but when writing  System.IO.File.Delete(Server.MapPath("~/uploads/loading.zip"))or directory.delete(path,true)it is giving error of permission denied...again if i manually change the permission of that folder for user type: users to modify,read,write full control then end user can delete the folder. how to solve it...pro grammatically

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

I have an Excel Connection using the MS OLE DB provider for Office 12 and a Data Flow task to load the data. The filename is set dynamically with an Expression and some variables. The DFT runs fine, then there are a couple of steps that do NOT reference the Excel connection, then there is a File System Task set to MOVE the file to a \Loaded folder. I keep getting the error " The process cannot access the file because it is being used by another process There are no other processes that would be access this file other than the SSIS package itself. I even put in a Script task the pauses 30 seconds (just in case the Data Flow hasn't had enough time to release the connection). Still get the error. Once the package finishes with this error and I stop the debugging, I can manually execute the one Move File task and it goes OK. How do I get the DFT to release the hold on this file?Todd C - MSCTS SQL Server 2005 - Please mark posts as answered where appropriate.

Session Expires on File Delete

Dear All, I am trying to delete Files and Directory through ASP.NET3.5 (C#)web application. But as soon as Directory\File is deleted It  automatically redirects me to Login Page. It means I am lossing my session on deleting File/Directory. Plz help me out.

How can i delete the file uploaded in my web page?

 Hi Experts. I am writing a simple web page that  users can upload an image file. After the file is uploaded, Users can fill up  other question in the web page. then users click the submit button to register them and the file is uploaded previously is move to special folder and is saved there. Know i want to delete the uploaded file if the user upload the file but dont click the submit button and close the web page. because i dont need the file uploaded until the user is not registered. I use Session_End event but i dont know why it dont work. With Regards. Mojtaba

Can't delete database-file

HelloThis has been driving me crazy all day and I've had to shutdown the website so I'm pretty stressed right now.I'm trying to delete ASPNETDB.MDF on a server but I keep getting the error "Cannot delete ASPNETDB: It is being used by another person or program". I've shut down both the website and the SQL Server service but the problem remains.I've also tried detaching it using 'sp_detach_db' but get:"CREATE DATABASE permission denied in database 'master'. An attempt to attach an auto-named database for file ASPNETDB.MDF failed. A database with the same name exists, or specified file cannot be opened".The server is running Windows Server 2003 and Microsoft SQL Server 2005 Express.Any suggestions?Thanks.

FCB::Open: Operating system error 32(The process cannot access the file because it is being used by

Hello all,I am running into an interesting scenario on my desktop.  I'm running developer edition on Windows XP Professional (9.00.3042.00 SP2 Developer Edition).  OS is autopatched via corporate policy and I saw some patches go in last week.  This machine is also a hand-me-down so I don't have a clean install of the databases on the machine but I am local admin.So, starting last week after a forced remote reboot (also a policy) I noticed a few of the databases didn't start back up.  I chalked it up to the hard shutdown and went along my merry way.  Friday however I know I shut my machine down nicely and this morning when I booted up, I was in the same state I was last Wenesday.  7 of the 18 databases on my machine came up withFCB:pen: Operating system error 32(The process cannot access the file because it is being used by another process.) occurred while creating or opening file 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\Test.mdf'. Diagnose and correct the operating system error, and retry the operation.and it also logs  FCB:pen failed: Could not open file C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\Test.mdf for file number 1. OS error: 32(The process cannot access the file because it is being used by another process.).I've caught references to the auto close feature being a possible culprit, no dice as the databases in question are set to Fal

The process could not be created for step 1 of job .....(reason: The system cannot find the file spe


Hi ,

I was trying your options by using "(operating system) cmdExec" to delete folders which were 15 days olders.  But here i am getting error if i look into view history of sql agent job... below is my command that i gave in Job step.

EXEC xp_cmdshell 'forfiles /p "z:\backup" -d 15 /c "cmd /c if @isDir==True echo RD /Q /S @FILE&RD /Q /S @FILE"'

And the error is :

The process could not be created for step 1 of job .....(reason: The system cannot find the file specified).  The Step failed.

but if i give this command in New Query Window, i am able to delete the folders successfully.

Please advice me if am wrong

R Anand

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend