You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Xamarin Forms中如何读取项目src文件夹下的file.txt文件

Xamarin.Forms 读取项目内src文件夹下txt文件的实现方案

直接使用File.ReadAllText传入路径的方式不适用Xamarin.Forms跨平台场景,不同平台文件系统规则差异大,推荐使用嵌入资源的方式读取,具体操作如下:


步骤1:配置文件生成属性

  • 找到项目中src目录下的file.txt,右键点击选择「属性」
  • 将「生成操作」字段设置为嵌入的资源(Embedded Resource),保存修改

步骤2:编写读取代码

在popuppage.xaml.cs中编写资源读取逻辑,嵌入资源的唯一标识规则为[项目默认命名空间].[文件夹层级].[文件名],文件夹层级之间用.代替路径分隔符:

using System.IO;
using System.Reflection;

// 写在Popuppage类内部的读取方法
private string GetFileTxtContent()
{
    // 请替换为你实际的资源ID,例如你的项目命名空间为DemoApp,就是DemoApp.src.file.txt
    string resId = "你的项目默认命名空间.src.file.txt";
    Assembly currentAssembly = Assembly.GetExecutingAssembly();

    using (Stream resStream = currentAssembly.GetManifestResourceStream(resId))
    using (StreamReader streamReader = new StreamReader(resStream))
    {
        return streamReader.ReadToEnd();
    }
}

问题排查

如果读取报空引用错误,可先遍历所有嵌入资源ID确认正确的资源名:

var allResIds = Assembly.GetExecutingAssembly().GetManifestResourceNames();
// 遍历输出allResIds即可看到file.txt对应的正确资源ID

内容的提问来源于stack exchange,提问作者Albvalort

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 06:48:03