Sharing violation on path in xamarin

好久不见. 提交于 2020-12-08 07:53:19

问题


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


回答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.




回答2:


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

using (var streamWriter = new StreamWriter (File.Create (path + "/" + "DoctorsList.xml")))


来源:https://stackoverflow.com/questions/23774186/sharing-violation-on-path-in-xamarin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!