Swanne
Swanne

Reputation: 98

Xamarin Forms Android - Save to file

Using Xamarin.Forms, has the way to write to file changed since Android 8.0?

I updated an existing project of mine, which includes a very simple function to write a text file to local storage, but after running the app and testing the write to file part, it just freezes and crashes out. There are no errors in the console or even evidence of it doing anything.

My function is as such:

public void Submit_Clicked(object sender, EventArgs e)
    {
        
        {
            string text = NameEntry.Text;

            string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string filename = Path.Combine(path, "DeviceProfile.txt");                
            File.WriteAllText(filename, text);                
            
        }
        catch(Exception ex)
        {
            DisplayAlert("Error:", ex.Message.ToString(), "Ok");
        }
        
        
    }

I cant see why this shouldn't work. Does someone know any reason why this wouldn't?

Upvotes: 1

Views: 1022

Answers (1)

Wendy Zang - MSFT
Wendy Zang - MSFT

Reputation: 10978

Like Jason said, the code below and the code you provided both work to write a text file to local storage.

string text = NameEntry.Text;
var path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "DeviceProfile.txt");
        using (var writer = File.CreateText(backingFile))
        {
            await writer.WriteLineAsync(text);
        }

You could read the text from the file to check.

 public async Task<string> ReadCountAsync()
    {
        var backingFile = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "DeviceProfile.txt");

        if (backingFile == null || !File.Exists(backingFile))
        {
            return null;
        }

        var text = string.Empty;
        using (var reader = new StreamReader(backingFile, true))
        {

            var str = await reader.ReadToEndAsync();
            
                text = str;

        }

        return text;
    }   

The path Environment.SpecialFolder.Personal you used to save the file is internal storage.

In Internal Storage, you couldn't see the files without root permission. If you want to view it, you could use adb tool. Please check the way in link.

How to write the username in a local txt file when login success and check on file for next login?

Upvotes: 2

Related Questions