Location>code7788 >text

Blazor/MAUI native interaction (II)

Popularity:537 ℃/2025-02-11 18:42:17

Maui Basics

Preferences is a static class provided by .NET MAUI for storing and retrieving application preferences (i.e. settings or configurations). It provides a simple key-value pair storage mechanism that can be used across platforms. Each platform uses its local storage mechanism to implement these functions, such as:

  • iOS uses NSUserDefaults
  • Using SharedPreferences on Android
  • Windows uses ApplicationDataContainer

Main functions

  1. Store values:
  • The Set method is used to store values. Supports multiple data types such as string, int, bool, double, float, long, and DateTime.
   ("key", "value");
   ("key", 123);
   ("key", true);
  1. Search values:
  • The Get method is used to retrieve stored values. If the key does not exist, the default value is returned.
   string value = ("key", "default_value");
   int number = ("key", 0);
   bool flag = ("key", false);
  1. Check if the key exists:
  • The ContainsKey method is used to check whether the specified key exists.
   bool exists = ("key");
  1. Remove key:
  • The Remove method is used to remove the specified key and its associated value.
   ("key");
  1. Clear all key-value pairs:
  • The Clear method is used to clear all stored key-value pairs.
   ();

Example

Here is a simple example showing how to use the Preferences class to store and retrieve application preferences:

//Storage value
 ("username", "Alex");
 ("isLoggedIn", true);
 ("loginCount", 5);

 // Search values
 string username = ("username", "default_user");
 bool isLoggedIn = ("isLoggedIn", false);
 int loginCount = ("loginCount", 0);

 // Check if the key exists
 bool hasUsername = ("username");

 // Remove key
 ("username");

 // Clear all key-value pairs
 ();

The Preferences class provides a simple and efficient way to manage application settings and configuration for cross-platform .NET MAUI applications

The file contains an internal partial class called NativeApi that provides several methods related to file operations.

get_config() method:

   public Task<string> get_config()
   {
       printerName = (PrinterNameKey, printerName);
       return (printerName);
   }   
  • This method gets the printer name (printerName) from the application's preferences.
  • Use the method to get the stored printer name, and if there is no storage, the default value is returned.
  • Returns a task containing the printer name.

open_file_dialog() method:

   public async Task<string> open_file_dialog()
   {
       //work in ui thread
       var res =
       await (async () =>
       {
           try
           {
               var result = await (new PickOptions());
               if (result == null)
               {
                   return "";
               }
               using var stream = await ();
               StreamReader reader = new StreamReader(stream);
               return Convert.ToBase64String(Encoding.(()));
           }
           catch (Exception e)
           {
               var err = ;
               return err;
           }
       });
       return res;
   }   
  • This method runs on a UI thread, opening the file selection dialog box.
  • Use the method to open the file selector.
  • If the user does not select a file, an empty string is returned.
  • If a file is selected, read the file contents and convert it to a Base64-encoded string.
  • If an exception occurs, an exception message is returned.

save_file(string data, string fileName) method:

   public async Task<string> save_file(string data, string fileName)
   {
       try
       {
           string targetFile = (, fileName);

           using FileStream outputStream = (targetFile);
           using StreamWriter streamWriter = new(outputStream);

           await (data);
           return $"file path:{("\\","\\\\")}";
       }
       catch (Exception e)
       {
           var err = ;
           return err;
       }
    }
  • This method saves the given data to the file with the specified file name.
  • Use the method to build the target file path, which is located in the application's data directory.
  • Use the method to open the file stream and write the data using StreamWriter.
  • After writing is completed, return the file path.
  • If an exception occurs, an exception message is returned.

These methods provide basic file operation functions, including getting configuration, opening file dialogs, and saving files

How to store custom objects in Preferences?

When storing custom objects in Preferences, since Preferences only supports basic data types (such as string, int, bool, etc.), you need to serialize the custom objects to string type and then store them. A common method of serialization is to use JSON.
Here is an example showing how to store and retrieve custom objects in Preferences:

Here is how each method works:

  1. Define custom objects
public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
}
  1. Use JSON Serialization and Deserialization

You can use the or library to perform JSON serialization and deserialization. The following example uses:

using ;

public void SaveUser(User user)
{
    string jsonString = (user);
    ("user", jsonString);
}
  1. Retrieve custom objects
public User? GetUser()
{
    string jsonString = ("user", );
    if ((jsonString))
    {
        return null;
    }
    return <User>(jsonString);
}
  1. Complete example
    Add the above method to your class, for example the NativeApi class:
using;

 internal partial class NativeApi: object
 {
     // Existing methods...

     public void SaveUser(User user)
     {
         string jsonString = (user);
         ("user", jsonString);
     }

     public User? GetUser()
     {
         string jsonString = ("user", );
         if ((jsonString))
         {
             return null;
         }
         return <User>(jsonString);
     }
 }

 public class User
 {
     public string Name { get; set; }
     public int Age { get; set; }
 }
illustrate
  1. SaveUser method: Serialize the User object into a JSON string and store it using the method.
  2. GetUser method: Retrieves the JSON string from Preferences and deserializes it into a User object. If the string is empty, return null.
    This way, you can store and retrieve custom objects in Preferences