File sharing violation occurs after creation of file?

18,075

Solution 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.

Solution 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.

Solution 3

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.

Solution 4

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
    }
Share:
18,075

Related videos on Youtube

Catlard
Author by

Catlard

i am alive! alive!

Updated on June 04, 2022

Comments

  • Catlard
    Catlard almost 2 years

    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?

    • Jason Massey
      Jason Massey over 11 years
      Might it be that File.Create is holding it open? I've always just let StreamWriter create the file.
  • Catlard
    Catlard over 11 years
    Fantastic. I will try that out. Cheers.
  • Catlard
    Catlard over 11 years
    Worked a treat. Thanks Mark.
  • Bob G
    Bob G over 6 years
    This doesn't appear to answer the question of the issue of sharing violation.