c# - 我应该在哪里找到 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"'
我不确定是否必须将 my.txt
放在.Android
or .IOS
proyect 的资源文件夹中。
这是我项目的结构。C#
读者类是Configure.cs
:
这是我的代码:
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 项目中,请创建或添加文件并确保 Build Action: EmbeddedResource。
GetManifestResourceStream
用于使用其Resource 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 ();
}
推荐阅读
- twitter - 是否可以按关注者数量搜索 Twitter 用户?
- development-environment - 从 CS50 开发环境迁移
- c - 偏航旋转:基于零的 mins/maxs 重新计算 mins/maxs
- php - 通过 PHP 从 csv 文件返回第一个结果
- bulletphysics - 在 PyByllet 中应用扭矩控制使物体飞离场景
- machine-learning - 使用高斯分布自动选择异常检测的特征
- c++ - 序列化 unordered_map 中的对象成员并存储到二进制文件中
- firebase - 在 Android Cordova 上使用 Firebase 身份验证的 Google 登录不起作用
- python - 功能问题程序
- arrays - 将多列中的文本合并为一列后聚集时删除尾随字符