File sharing violation occurs after creation of fi

2019-08-08 15:43发布

问题:

So, I'm attempting to create a .txt file, and then write some silly data to it. But I'm getting a sharing violation. I sense that it may be because I'm attempting to create a StreamWriter for a file directly after creating it, but that doesn't make sense. So I'm a bit lost. I've tried removing all the other StreamWriters and Readers in the class except for the erroneous line, and I'm still getting a violation. The error I'm getting,

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)

Points to the line:

StreamWriter sw = new StreamWriter(statusTxtPath);

In the following function:

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;
    }

Any idea why that dog won't hunt?

回答1:

Is there a reason why you are wanting to create the file then reopen it to write to it. StreamWriter has an method that will do just that. It will create a new file if it doesn't exist.

From above link:

Initializes a new instance of the StreamWriter class for the specified file on the specified path, using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.



回答2:

StreamWriter could not access the file because File.Create returned a FileStream you did not consume.

As mentioned above, the File.Create is not necessary. You could also use:

using (var writer = new StreamWriter(File.Create(statusTxtPath)))
{
   // do work here.
}

which will consume the file stream and close it. Whenever working with streams and most classes that interact with streams, be sure to use the using() block to ensure handles are released properly.



回答3:

It might be happening because the StreamWriter did not release the un-managed resources yet: Try to use the block of using instead of opening and closing it manually.

using (StreamWriter writer = new StreamWriter(statusTxtPath))
    {
        // do work here
    }


回答4:

I'm new in this programming language, I know some Ansi C mainly from programming micro controllers but I'm now learning C# and I was having kind of the same problem.

System.IO.IOException
Sharing violation on path /.../...

I found that having the following code, raises an exception.

if(!File.Exists(path))
   File.Create(path);

The solution I found to solve this actually uses less and simpler code.

File.AppendAllText(path, str);

With this line the program will open the file if it already exists and append the text to the end of it, if it doesn't exist will create it and append the text.

Being:  path -> the path of the file
            str    -> the text that you want to write to the file

I found a hint for the solution on this Xamarin forum page.



回答5:

I also face the same issue with multithreaded programming ,I thoughts its Thread synchronization issue, but problem is after File.Create() I used StreamWriter. Here you can try instead of using two different steps you can combine in single step. this code works fine to me.

using (var writer = new StreamWriter(File.Exists(path) ? File.Open(path, FileMode.Open) : File.Create(path)))
{
    writer.Write(str);
    writer.Close();
}