简体   繁体   中英

How to read from local storage in xamarin android?

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

In This Way I want to read an html from my local storage But while readalltext am getting exception System.IO.IOException: Sharing violation on path /storage/emulated/0/first.html

When you do this

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

it opens/creates a file at filepath . So after this the file always exists (given the path is correct and permissions allow). Then you try to read it but you have it open for writing so this will not be allowed.

If you're trying to see if the file exists and if not, write to it, then move the StreamWriter creation inside the check

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM