.net 如何在maui c#中使用字符串在文件中存储任何变量并在运行时加载它?

gzszwxb4  于 2023-10-21  发布在  .NET
关注(0)|答案(1)|浏览(122)

我想保存变量在一个文件中,将有特定的键,我想加载它使用该键。建议我两个函数(可以采取和使用任何变量和类作为参数),作为跨平台的方法在maui C#。我尝试了下面的代码,并得到了错误。
试了这个代码:

`public static void StoreData<T>(string key, T value)
{
    
    try
    {
        // Load existing data or create a new dictionary
        Dictionary<string, T> data;

        string filePath = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AppInfo.Current.Name), "data.json");

        if (!Directory.Exists(Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                AppInfo.Current.Name)))

        {
            Directory.CreateDirectory(Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                AppInfo.Current.Name));
        }

        if (!File.Exists(filePath))
        {
            File.Create(filePath);
        }

        using (StreamReader reader = new StreamReader(filePath))
        {
            data = new Dictionary<string, T>();
            string json = reader.ReadToEnd();
            data = JsonSerializer.Deserialize<Dictionary<string, T>>(json);
        }

        data[key] = value;

        // Add or update the value associated with the key

        // Serialize and save the updated data to the file
        using (StreamWriter writer = new StreamWriter(filePath))
        {
            string json = JsonSerializer.Serialize(data);
            writer.Write(json);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to save data: {ex.Message}");
    }
}

// Load data based on a key as an identifier
public static T LoadData<T>(string key, T defaultValue = default)
{
    try
    {
        // Load existing data or return the default value
        Dictionary<string, T> data;
        string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "data.json");

        if (File.Exists(filePath))
        {
            using (StreamReader reader = new StreamReader(filePath))
            {
                string json = reader.ReadToEnd();
                data = JsonSerializer.Deserialize<Dictionary<string, T>>(json);

                if (data != null)
                {
                    if (data.ContainsKey(key))
                    {
                        return data[key];
                    }
                }
            }
        }

        return defaultValue;
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to load data: {ex.Message}");
        return defaultValue;
    }
}`

误差

  • System.Text.Json.JsonException HResult=0x80131500 Message=The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0. Source=System.Text.Json StackTrace: at System.Text.Json.ThrowHelper.ReThrowWithPath(ReadStack& state, JsonReaderException ex) at System.Text.Json.Serialization.JsonConverter1.ReadCore(Utf8JsonReader& reader,JsonSerializerOptions options,ReadStack& state)at System.发短信杰森JsonSerializer。系统上的ReadFromSpan[TValue](ReadOnlySpan1 utf8Json, JsonTypeInfo jsonTypeInfo, Nullable1 actualByteCount)。发短信杰森JsonSerializer。系统上的ReadFromSpan[TValue](ReadOnlySpan1 json,JsonTypeInfo jsonTypeInfo)。发短信杰森JsonSerializer。将[TValue](String json,JsonSerializerOptions options)初始化到book_companion_3.DataBase. StoreData [T](String key,T value),以K表示:\Windows For Programming\Projects\Visual Studio\Apps\Maui\book companion 3\DataTool.cs:第78行

此异常最初是在此调用堆栈中引发的:[外部代码]
内部异常1:JsonReaderException:输入不包含任何JSON标记。当isFinalBlock为true时,输入应以有效的JSON标记开始。行号:0| BytePositionInLine:0. `

68bkxrlz

68bkxrlz1#

我测试了你的代码,遇到了一些问题:

1.关于以下部分代码:

using (StreamReader reader = new StreamReader(filePath))
        {
            data = new Dictionary<string, T>();
            string json = reader.ReadToEnd();
            data = JsonSerializer.Deserialize<Dictionary<string, T>>(json);
        }

当您的数据类型在这次和上次之间不同时,这将引发数据转换异常。

2.存储和加载的文件路径不同。

在存储中,它是:
Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AppInfo.Current.Name), "data.json");
但在加载中,它是:
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "data.json");
它错过了AppInfo.Current.Name。所以我删除了第一个问题中的代码,并更改了加载方法中的路径。

public partial class MainPage : ContentPage
    {
        public static void StoreData<T>(string key, T value)
        {
            try
            {
                // Load existing data or create a new dictionary
                Dictionary<string, T> data;

                string filePath = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AppInfo.Current.Name), "data.json");

                if (!Directory.Exists(Path.Combine(
                        Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                        AppInfo.Current.Name)))

                {
                    Directory.CreateDirectory(Path.Combine(
                        Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                        AppInfo.Current.Name));
                }

                if (!File.Exists(filePath))
                {
                    File.Create(filePath);
                }
                data = new Dictionary<string, T>();
                data[key] = value;

                // Add or update the value associated with the key

                // Serialize and save the updated data to the file
                using (StreamWriter writer = new StreamWriter(filePath))
                {
                    string json = JsonSerializer.Serialize(data);
                    writer.Write(json);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to save data: {ex.Message}");
            }
        }

// Load data based on a key as an identifier
        public static T LoadData<T>(string key, T defaultValue = default)
        {
            try
            {
                // Load existing data or return the default value
                Dictionary<string, T> data;
                string filePath = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), AppInfo.Current.Name), "data.json");
                if (File.Exists(filePath))
                {
                    using (StreamReader reader = new StreamReader(filePath))
                    {
                        string json = reader.ReadToEnd();
                data = JsonSerializer.Deserialize<Dictionary<string, T>>(json);

                        if (data != null)
                        {
                            if (data.ContainsKey(key))
                            {
                                return data[key];
                            }
                        }
                    }
                }

                return defaultValue;
            }
            catch (Exception ex)
            {
            Console.WriteLine($"Failed to load data: {ex.Message}");
            return defaultValue;
            }
        }

        public MainPage()
        {
            InitializeComponent();
        }

        private void Button_Clicked(object sender, EventArgs e)
        {
           StoreData<List<string>>("hello",new List<string>() { "ASD","AAA"});
        }

        private void Button_Clicked_1(object sender, EventArgs e)
        {
           var value = LoadData<List<string>>("hello",new List<string>());
        }
    }

之后,我可以存储数据并加载它。

相关问题