创建文件后发生文件共享冲突?

2023-12-13

因此,我尝试创建一个 .txt 文件,然后向其中写入一些愚蠢的数据。但我遇到了共享违规。我感觉这可能是因为我试图在创建文件后直接为其创建 StreamWriter,但这没有意义。所以我有点失落。我已经尝试删除类中除错误行之外的所有其他 StreamWriters 和 Reader,但我仍然遇到违规。我收到的错误,

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 类的新实例。如果该文件存在,则可以覆盖或附加该文件。如果该文件不存在,则此构造函数将创建一个新文件。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

创建文件后发生文件共享冲突? 的相关文章

随机推荐