在 xamarin 路径上共享违规 [英] Sharing violation on path in xamarin

查看:54
本文介绍了在 xamarin 路径上共享违规的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Android 编程非常陌生.我有一个代码,它在指定的文件夹中创建一个文件,然后尝试向其中写入一些内容.如下图:

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>");
        }

在线使用(var streamWriter = new StreamWriter(filename,true)),我收到路径上的共享冲突错误.

有人可以指出我到底哪里出错了,并为我提供解决方案.

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

谢谢,安尼班

推荐答案

为什么要创建文件然后重新打开它以写入文件.StreamWriter 有一个方法可以做到这一点.如果它不存在,它将创建一个新文件.

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.

使用默认编码和缓冲区大小为指定路径上的指定文件初始化 StreamWriter 类的新实例.如果文件存在,它可以被覆盖或附加到.如果文件不存在,此构造函数会创建一个新文件.

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 无法访问该文件,因为 File.Create 返回了一个您没有使用的 FileStream.

StreamWriter could not access the file because File.Create returned a FileStream you did not consume.

如上所述,File.Create 不是必需的.您还可以使用:

As mentioned above, the File.Create is not necessary. You could also use:

using (var writer = new StreamWriter(File.Create(statusTxtPath)))
{
   // do work here.
}

这将消耗文件流并关闭它.每当使用流和大多数与流交互的类时,请务必使用 using() 块以确保正确释放句柄.

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.

这篇关于在 xamarin 路径上共享违规的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆