简体   繁体   English

文件已在使用中FileAccess C#

[英]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. 每当我尝试将数据输出到.dat文件时,都会收到一条错误消息,指出该文件已在使用中。 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. EDT:事实证明,它不允许我保存到一个空文件,所以我创建了一个新的void来输入数据,然后它允许我保存该文件。

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. 我注意到您没有使用using语句。 If an exception were thrown in the block of code you show, outputFile.Close() would never execute, leaving the file open. 如果在您显示的代码块中引发了异常,则将永远不会执行outputFile.Close() ,从而使文件保持打开状态。

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 using关键字是的语法快捷方式

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 (也将其关闭),无论是否引发异常。

您可以尝试以下方法:

outFile.Dispose();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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