Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

I am getting binary data from a SQL Server database field and am creating a document locally in a directory my application has permissions. However I am still getting the error specified in the title. I have tried numerous suggestions posted on the web including those suggested in previous posts on Stackoverflow. I have also used ProcessExplorer > Find Handle to locate the lock and it returns nothing as if the file is not locked.

I am using the code below to save the file to the file system and I then try to copy this file to a new location later in the application process within another method. It is this copy method that takes the path of the newly created file that throws the exception.

The file itself is created with its content and i can open it through Windows Explorer without any problems.

Am I missing something completely obvious? Am I creating the file correctly from the database? Any help on solving or better diagnosing the problem would be much appreciated.

// Get file from DB
FileStream fs = new FileStream(
    "C:\myTempDirectory\myFile.doc", FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter br = new BinaryWriter(fs);
br.Write("BinaryDataFromDB");
fs.Flush();
fs.Close();
fs.Dispose();

// Copy file
File.Copy(sourceFileName, destinationFilename, true);
like image 986
Cragly Avatar asked Feb 08 '10 21:02

Cragly


People also ask

How do you fix because it is being used by another process?

Process cannot access file because it is being used by another process error message. To resolve this error: Press Ctrl + Alt + Delete, then click Task Manager. Ensure you're on the Processes tab.


2 Answers

Try adding a call to GC.Collect() after you have disposed of your streams to force the garbage collector to clean up.

// Get file from DB 
using(FileStream fs = new FileStream("C:\myTempDirectory\myFile.doc", FileMode.OpenOrCreate, FileAccess.Write)) 
using(BinaryWriter br = new BinaryWriter(fs))
{
   br.Write("BinaryDataFromDB"); 
   fs.Flush(); 
}

//Force clean up
GC.Collect();

// Copy file 
File.Copy(sourceFileName, destinationFilename, true); 
like image 68
Jesper Palm Avatar answered Sep 26 '22 02:09

Jesper Palm


change your code as follows, the problem is that the the filestream isn't being garbage collected when you need it to:

    // Get file from DB 
using (FileStream fs = new FileStream("C:\myTempDirectory\myFile.doc", FileMode.OpenOrCreate, FileAccess.Write)) 
{
    BinaryWriter br = new BinaryWriter(fs); 
    br.Write("BinaryDataFromDB"); 
    fs.Flush(); 
    fs.Close(); 
}

// Copy file 
File.Copy(sourceFileName, destinationFilename, true);
like image 25
NotMe Avatar answered Sep 26 '22 02:09

NotMe