简体   繁体   中英

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.

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.

您可以尝试以下方法:

outFile.Dispose();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM