如何从xamarin android中的本地存储中读取?

时间:2017-07-11 16:37:51

标签: c# android xamarin

        var sdcardpath = Android.OS.Environment.ExternalStorageDirectory.Path;
        var filepath = System.IO.Path.Combine(sdcardpath, "first.html");
        System.IO.StreamWriter writer = new StreamWriter(filepath, true);
        if (!System.IO.File.Exists(filepath))
        {
            writer.Write(htmltext);
        }
        else
        {
            var txt = System.IO.File.ReadAllText(filepath);
        }

以这种方式我想从我的本地存储中读取一个html但是readalltext正在异常     System.IO.IOException:在路径/storage/emulated/0/first.html

上共享违规

1 个答案:

答案 0 :(得分:0)

当你这样做时

System.IO.StreamWriter writer = new StreamWriter(filepath, true);

它会在filepath打开/创建一个文件。所以在此之后文件始终存在(给定路径正确并且权限允许)。然后你尝试阅读它,但你打开它写,所以这是不允许的。

如果您正在尝试查看该文件是否存在,如果没有,请写入,然后将StreamWriter创建内容移到支票

if (!System.IO.File.Exists(filepath))
{
    using (var writer = new StreamWriter(filepath, true))
    {
        writer.Write(htmltext);
    }
}
else
{
    var txt = System.IO.File.ReadAllText(filepath);
}