首页 > 解决方案 > 如何在 Xamarin Forms 中访问存储在共享项目中的文件?

问题描述

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

Visual Studio 解决方案页面

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

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

AppDomain.CurrentDomain.BaseDirectory

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

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

标签: visual-studioxamarinxamarin.forms

解决方案


这就是我为共享项目中的 JSON 文件所做的(使用 PCL)。正如 Jason 在评论中指出的那样,如果您使用的是 .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";

推荐阅读