因此,我试图创建一个.txt文件,然后向其中写入一些愚蠢的数据。但是我遇到了共享冲突。我感觉可能是因为我试图在创建文件后直接为文件创建StreamWriter,但这没有任何意义。所以我有点迷路。我尝试删除该类中除错误行以外的所有其他StreamWriter和Readers,但仍然遇到违规情况。我得到的错误

IOException: Sharing violation on path C:\Users\USER\Desktop\Accessible\Assets\IO\Books\A community of learners\frog\frog_status.txt
System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options)
System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share)
(wrapper remoting-invoke-with-check) System.IO.FileStream:.ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare)


指向该行:

StreamWriter sw = new StreamWriter(statusTxtPath);


在以下功能中:

private IEnumerator GatherStatusInfo(string folderPath, string mediaName) {

        string statusTxtPath = folderPath + @"/" + mediaName + "_status.txt";
        _currentInfoBeingCreated._readingStatusTxtPath = statusTxtPath;

        if(BuildManager.instance._isResetStatusFilesWhenStarting) {
            if(File.Exists(statusTxtPath))
                File.Delete(statusTxtPath);
        }

        if(!File.Exists(statusTxtPath)) {
            File.Create(statusTxtPath);
            StreamWriter sw = new StreamWriter(statusTxtPath);
            sw.WriteLine(MediaStatus.Unread);
            sw.WriteLine("0");
            _currentInfoBeingCreated._status = MediaStatus.Unread;
            _currentInfoBeingCreated._pageLastRead = 0;
            sw.Flush();
            sw.Close();

        } else {

            StreamReader statusReader = new StreamReader(statusTxtPath);
            _currentInfoBeingCreated._status = (MediaStatus) Enum.Parse(typeof(MediaStatus), statusReader.ReadLine());
            _currentInfoBeingCreated._pageLastRead = (int) ConversionUtils.instance.String2Float(statusReader.ReadLine());
            statusReader.Close();
        }

        yield return 0;
    }


知道为什么那只狗不会打猎吗?

最佳答案

为什么要创建文件然后重新打开文件以写入文件,这是有原因的。 StreamWriter有一个可以做到这一点的方法。如果不存在,它将创建一个新文件。

从上面的链接:


  使用默认编码和缓冲区大小为指定路径上的指定文件初始化StreamWriter类的新实例。如果文件存在,则可以将其覆盖或附加。如果该文件不存在,则此构造方法将创建一个新文件。

10-07 19:39
查看更多