微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我应该在哪里找到 Xamarin.Forms 上的配置或初始化文件?

如何解决我应该在哪里找到 Xamarin.Forms 上的配置或初始化文件?

我正在尝试将配置文件加载到我的 Xamarin.Forms 项目中。这个文件一个简单的 .txt,它有一个带有配置属性JSON。我的 C# 阅读器类位于我的文件的同一文件夹中(在 Xamarin.Form 解决方案中),但它说:

System.IO.FileNotFoundException:'Could not find file "/data/user/0/com.companyname.nucleo/files/.local/share/configure.txt"'

我不确定是否必须在 .txt.Android 项目的资源文件夹中找到我的 .IOS

这是我的项目的结构。 C# 阅读器类是 Configure.cs:

enter image description here

这是我的代码

string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"configure.txt");
string text = File.ReadAllText(fileName);

Console.WriteLine("Contents of WriteText.txt = {0}",text);

我也试过这个,

var assembly = IntrospectionExtensions.GetTypeInfo(typeof(Configure)).Assembly;
Stream stream = assembly.GetManifestResourceStream("WorkingWithFiles.configure.txt");
string text = "";
using (var reader = new StreamReader(stream)) {
     text = reader.ReadToEnd();
}
System.Console.WriteLine("Contents of WriteText.txt = {0}",text);

但是在这种情况下它会抛出这个异常:

System.ArgumentNullException: 'Value cannot be null.

解决方法

要将文件嵌入 Xamarin 项目,请创建或添加文件并确保构建操作:EmbeddedResource

enter image description here

GetManifestResourceStream 用于使用其资源 ID 访问嵌入文件。

默认情况下,资源 ID 是文件名 前缀 是它嵌入的项目的默认命名空间 - 在您的情况下是程序集可能是 NoguianaNucleo,文件名是 configure.txt,所以资源 ID 是 NoguianaNucleo.configure.txt

使用以下代码,您应该能够读取文件:

var assembly = IntrospectionExtensions.GetTypeInfo(typeof(LoadResourceText)).Assembly;
Stream stream = assembly.GetManifestResourceStream("NoguianaNucleo.configure.txt");
string text = "";
using (var reader = new System.IO.StreamReader (stream))
{  
    text = reader.ReadToEnd ();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。