【问题标题】:How to access file stored in shared project in Xamarin Forms?如何在 Xamarin Forms 中访问存储在共享项目中的文件?
【发布时间】:2020-12-24 03:45:28
【问题描述】:

我在共享项目中有一个名为 Documentation 的文件夹,在本例中名为 App2。如何访问存储在 Documentation 文件夹中的文件?下面的附图显示了项目结构。

Visual Studio Solution Page

我已经尝试了以下命令,但它们不起作用:

System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

AppDomain.CurrentDomain.BaseDirectory

System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

如果访问该文件夹中的文件很麻烦,我愿意听取其他选择。

【问题讨论】:

  • 那不是启动项目。启动项目将是 iOS 或 Android 项目。要访问共享项目中的文件,最好将它们存储为嵌入式资源。
  • @Jason 哦,我不知道。如何将它们存储为嵌入式资源?或者如果我要将文件存储在 iOS 和 Android 项目中,我该如何访问它们?
  • 您可以将它们作为构建类型内容存储在平台项目中,然后使用相对路径读取。如果你想走嵌入式资源路线,那是有据可查的,我不需要重复。
  • 谢谢,我去看看

标签: visual-studio xamarin xamarin.forms


【解决方案1】:

这就是我为共享项目中的 JSON 文件所做的(使用 PCL)。正如 Jason 在 cmets 中指出的那样,如果您使用的是 .NET Standard,则可以在共享项目中简单地定义 GetSharedFile 方法,而不是创建特定于平台的引用。

  1. 将文件添加到共享项目并设置为Embedded Resource

  2. 在你的共享项目中创建一个IFileHelper 接口

    public interface IFileHelper {
        Stream GetSharedFile(string fileResourceName);
    }
  1. 使用以下内容在每个项目(Android 和 iOS)中创建一个新的 FileHelper
    public class FileHelper : IFileHelper {
        public Stream GetSharedFile(string fileResourceName) {
            Type type = typeof(IFileHelper); // We could use any type here, just needs to be something in your shared project so we get the correct Assembly below
            return type.Assembly.GetManifestResourceStream(fileResourceName);
        }
    }
  1. 在您的共享项目中添加一个文档处理程序类。如下所示(确保更改 App 命名空间以匹配您的命名空间):
    public class Documentation {
      private const string ResourcePath = "App.Documentation.index.html"; // App would be your application's namespace, you may need to play with the Documentation path part to get it working

      public string GetDocs() {
          IFileHelper helper = DependencyService.Get<IFileHelper>(); // Your platform specific helper will be filled in here

          Stream stream = helper.GetSharedFile(ResourcePath);
          using (stream)
          using (StreamReader reader = new StreamReader(stream)) {
              return reader.ReadToEnd(); // This should be the file contents, you could serialize/process it further
          }
      }
    }

我主要是用手写的,所以如果有什么问题,请告诉我。如果您无法加载文件,我建议您尝试将其放入共享项目的根目录中,然后将上面代码中的 ResourcePath 更改为以下内容(再次使用您应用的命名空间而不是 App):

private const string ResourcePath = "App.index.html";

【讨论】:

  • 您应该能够直接在共享的 .NET Standard 项目中执行此操作,而无需使用 DependencyService
猜你喜欢
  • 2021-02-17
  • 2016-06-16
  • 2021-09-23
  • 1970-01-01
  • 2015-08-17
  • 1970-01-01
  • 2017-07-19
  • 2022-11-18
  • 1970-01-01
相关资源
最近更新 更多