Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing violation on path in xamarin

Tags:

path

sharing

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

like image 575
Anirban Avatar asked May 21 '14 04:05

Anirban


2 Answers

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.

like image 78
Gaurav Deochakke Avatar answered Nov 07 '22 15:11

Gaurav Deochakke


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

using (var streamWriter = new StreamWriter (File.Create (path + "/" + "DoctorsList.xml")))
like image 32
Anirban Avatar answered Nov 07 '22 14:11

Anirban