问题描述
我正在尝试将配置文件加载到我的 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
:
这是我的代码:
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。
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 ();
}