首页 > 解决方案 > 如何在 xamarin.forms 中获取应用程序本身的目录

问题描述

我在 Xamarin.Forms 项目中为应用程序(不是 Android 或 iOS 版本)创建的 Resources 文件夹中有一个 .txt 文件,我想知道如何在应用程序加载后立即访问该文件。我尝试使用路径“Resources/tips.txt”(“tips”是文件的名称)创建一个 StreamReader,但这不起作用,因为显然,此时的当前目录什么都不是。如何获取应用程序本身的目录以便我可以访问该文件夹?

标签: c#xamarin.formsfile-io

解决方案


资源不是文件,您不使用文件路径来访问它们

// MyClass is a class in the same assembly as your resource
var assembly = IntrospectionExtensions.GetTypeInfo(typeof(MyClass)).Assembly;

// see linked docs for notes about resource naming
Stream stream = assembly.GetManifestResourceStream("MyResourceName");

string text = "";

using (var reader = new System.IO.StreamReader (stream))
{  
    text = reader.ReadToEnd ();
}

推荐阅读