程序说文件已在使用但我关闭了它 C#

Program saying file already in use but i closed it C#

private void buttonAdd_Click(object sender, EventArgs e)
        {
            string path = @"comics.txt";
            if (!File.Exists(path))
            {
                var myComicsFile = File.Create(path);
                myComicsFile.Close();
                FileStream file = new FileStream("comics.txt", FileMode.Open, FileAccess.ReadWrite);
                TextWriter write = new StreamWriter(path);
            }
            else if (File.Exists(path))
            {
                FileStream file = new FileStream("comics.txt", FileMode.Open, FileAccess.ReadWrite);
                TextWriter write = new StreamWriter(path);
            }
        }

我一直收到错误 System.IO.IOException:'The process cannot access the file because it is being used by another process' 我以为我已经通过在创建文件后关闭文件来修复它并打开它,但我仍然收到错误消息。不确定正确的解决方案是什么。任何帮助将不胜感激。

您可以嵌套 using,通过自动调用 dispose 来消除许多潜在问题(就像您已经遇到的那样)。例如

using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
    {
        using (BufferedStream bs = new BufferedStream(fs))
        {
            using (System.IO.StreamReader sr = new StreamReader(bs))
            {
                string output = sr.ReadToEnd();
            }
        }
    }

首先,不需要创建一个空文件并打开它,而是使用适当的FileMode代替

FileMode.OpenOrCreate

OpenOrCreate

Specifies that the operating system should open a file if it exists; otherwise, a new file should be created. If the file is opened with FileAccess.Read, Read permission is required. If the file access is FileAccess.Write, Write permission is required. If the file is opened with FileAccess.ReadWrite, both Read and Write permissions are required.

当您使用 BCL 方法时,请始终检查文档以获取有关如何使用它的线索,特别是查看是否支持 IDisposable 如果它确实总是使用 using 语句,当您可以

using Statement (C# Reference)

Provides a convenient syntax that ensures the correct use of IDisposable objects.

简而言之,您本可以做到这一点

 using (var file = new FileStream("comics.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
    using(var TextWriter write = new StreamWriter(file))
    {
       // stuff here
    }

基本上,当 using 带有流派生的 using 语句时,它会关闭并释放任何非托管资源,如文件句柄。在你的情况下,你已经离开了文件句柄悬空,因此你的问题

使用“using”语句确保文件已关闭。

参考: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement