Sharing violation on path in xamarin

Anirban picture Anirban · May 21, 2014 · Viewed 11.2k times · Source

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

Answer

Gaurav Deochakke picture Gaurav Deochakke · May 21, 2014

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.