RonnieB555
RonnieB555

Reputation: 13

File is already in use FileAccess C#

public void WriteListToFile(Lists lists, string filePath)
    {
        FileStream outFile;
        BinaryFormatter bFormatter = new BinaryFormatter();

        // Ppen file for output
        outFile = new FileStream(filePath, FileMode.Create, FileAccess.Write);

        // Output object to file via serialization
        bFormatter.Serialize(outFile, lists);

        // Close file
        outFile.Close();
    }

Whenever I try to output data to a .dat file I get an error saying that the file is already in use. How do I fix this?

EDT: Turns out it wouldn't let me save to an empty file so I create a new void to input data and then it allowed me to save over the file.

Upvotes: 1

Views: 2131

Answers (2)

Eric J.
Eric J.

Reputation: 150108

The immediate answer is "release the lock that some process has on the file".

Something already has the file open. You need to look at code and other processes that may access that file to find the root cause.

I note that you're not making use of using statements. If an exception were thrown in the block of code you show, outputFile.Close() would never execute, leaving the file open.

Try rewriting your code (and any similar code) like

public void WriteListToFile(Lists lists, string filePath)
{    
    BinaryFormatter bFormatter = new BinaryFormatter();

    // Ppen file for output
    using (FileStream outFile = new FileStream(filePath, FileMode.Create, FileAccess.Write))
    {

        // Output object to file via serialization
        bFormatter.Serialize(outFile, lists);

        // Close file
        outFile.Close();
    }
}

The using keyword is a syntactic shortcut for

var outFile = new FileStream(filePath, FileMode.Create, FileAccess.Write);
try 
{
    // Do stuff with outFile
}
finally 
{
    outFile.Dispose();
}

and ensures that outFile is disposed (which also closes it) whether or not an exception is thrown.

Upvotes: 5

j.s.banger
j.s.banger

Reputation: 412

you can try this:

outFile.Dispose();

Upvotes: 0

Related Questions