Saving and loading files in Xamarin Android

Question:

How can you save an array of strings to a file, and also load this file back into the program.

Answer:

  1. "File System Plugin for Xamarin and Windows" or many other plugins to help you. It will create a file, save data, read.

public async Task CreateRealFileAsync () {// get hold of the file system IFolder rootFolder = FileSystem.Current.LocalStorage;

        // create a folder, if one does not exist already
        IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder", CreationCollisionOption.OpenIfExists);

        // create a file, overwriting any existing file
        IFile file = await folder.CreateFileAsync("MyFile.txt", CreationCollisionOption.ReplaceExisting);

        // populate the file with some text
        await file.WriteAllTextAsync("Sample Text...");

}

  1. а потом в платформе реализует Share Service.
    Android:

    public class Share: IShare
    {
    private readonly Context _context;
    public Share()
    {
    _context = Android.App.Application.Context;
    }

    public Task Show(string title, string message, string filePath)
    {
        var extension = filePath.Substring(filePath.LastIndexOf(".") + 1).ToLower();
        var contentType = string.Empty;
    
        // You can manually map more ContentTypes here if you want.
        switch (extension)
        {
            case "pdf":
                contentType = "application/pdf";
                break;
            case "png":
                contentType = "image/png";
                break;
            default:
                contentType = "application/octetstream";
                break;
        }
    
        var intent = new Intent(Intent.ActionSend);
        intent.SetType(contentType);
        intent.PutExtra(Intent.ExtraStream, Uri.Parse("file://" + filePath));
        intent.PutExtra(Intent.ExtraText, string.Empty);
        intent.PutExtra(Intent.ExtraSubject, message ?? string.Empty);
    
        var chooserIntent = Intent.CreateChooser(intent, title ?? string.Empty);
        chooserIntent.SetFlags(ActivityFlags.ClearTop);
        chooserIntent.SetFlags(ActivityFlags.NewTask);
        _context.StartActivity(chooserIntent);
    
        return Task.FromResult(true);
    }
    

    }

  2. Реализуйте ассоциацию приложения с вашим типом файлов, чтобы открыть на втором телефоне(к примеру при получении по email).
    Ну или свой велосипед по передачи между телефонами.

Scroll to Top