首页 > 解决方案 > 我应该在哪里找到 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放在.Androidor .IOSproyect 的资源文件夹中。

这是我项目的结构。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.

标签: c#xamarinxamarin.formsxamarin.androidxamarin.ios

解决方案


要将文件嵌入到 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 ();
}

推荐阅读