gpt4 book ai didi

c# - Xamarin 文件处理文档 - SpecialFolder.LocalApplicationData 不存在

转载 作者:行者123 更新时间:2023-11-29 23:30:33 24 4
gpt4 key购买 nike

Documentation for Xamarin说您可以使用以下内容读取文本文件:

File.ReadAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "score.txt"))

“score.txt”在我的解决方案中是一个文本文件,但是,在编译和执行该代码时找不到该文件:

FileNotFoundException

我可以通过以下方式成功读取我的解决方案中的文本文件:

using (var stream = await FileSystem.OpenAppPackageFileAsync("score.txt"))
using (var reader = new StreamReader(stream))

但是我不能使用流阅读器,因为我需要在应用程序打开时读取文件,所以它不能是异步的。

我哪里做错了还是文档有误?

最佳答案

File.ReadAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "score.txt"))

LocalApplicationData 不是 native bundle Assets 的位置。您需要先将其从只读应用程序包中复制出来。

However I can't use a stream reader as I need to read the file when the app opens so it cannot be asynchronous.

您可以在多个区域执行此操作更改为 OnStart 覆盖您的表单的应用程序子类(通常是 App)以允许 await

protected async override void OnStart()
{
...

您也可以在第一页 OnAppearing override 中执行此操作:

protected async override void OnAppearing()
{
...

Xamarin.Essentials OpenAppPackageFileAsync 将流返回到“ native ”Android Assets 或 iOS 包资源等。因此您需要将 score.txt 文件复制到 native 项目

安卓:

使用 AndroidResource 的构建操作将 score.txt 添加/复制到您的 Xamarin.Android 项目 Assets 中

enter image description here

iOS:

使用 BundleResource 的构建操作将 score.txt 添加/复制到您的 Xamarin.iOS 项目资源(从技术上讲,在任何地方,但对于组织资源来说效果很好)

enter image description here

关于c# - Xamarin 文件处理文档 - SpecialFolder.LocalApplicationData 不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52767430/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com