Sharing violation on path in xamarin

13,289

Solution 1

Why do you 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.

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.

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 2

Ok...I have managed to resolve the issue...by using

using (var streamWriter = new StreamWriter (File.Create (path + "/" + "DoctorsList.xml")))
Share:
13,289
Anirban
Author by

Anirban

Updated on June 09, 2022

Comments

  • Anirban
    Anirban almost 2 years

    I'm very new to Android programming. I have a code which creates a file in a designated folder and then tried to write something to it. Like below:

            path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            var filename = Path.Combine(path, "Test.xml");
            Directory.CreateDirectory (path);
            if (!File.Exists (path + "/" + "Test.xml")) {
                File.Create (path + "/" + "Test.xml");
            }
            using (var streamWriter = new StreamWriter(filename, true))
            {
                streamWriter.WriteLine("<?xml version='1.0' encoding='utf-8'?>");
                streamWriter.WriteLine ("<Apples>");
                streamWriter.WriteLine ("</Apples>");
            }
    

    In line using (var streamWriter = new StreamWriter(filename, true)), I'm getting the Sharing Violation on path error.

    Could someone please point me as to exactly where I'm going wrong and provide me a solution.

    Thanks, Anirban

  • Ivo Smits
    Ivo Smits over 2 years
    It's not just that the File.Create call in the original code is not necessary, it actually creates a FileStream object with exclusive write access to the file. This object will be cleaned up eventually by the garbage collector, but (apparently) not yet by the time the StreamWriter attempts to open the file again. Changing File.Create line to File.Create (path + "/" + "Test.xml").Dispose(); should also fix the sharing violation, although the proposed solution is better.