【问题标题】:Get a StreamReader from a resource file in Xamarin Android从 Xamarin Android 中的资源文件获取 StreamReader
【发布时间】:2021-02-14 15:10:11
【问题描述】:

我在 Xamarin Android 项目的 Resource 文件夹中有一个名为 dictionary.txt 的文本文件。我需要一个 StreamReader 来读取文件。我即兴编写了以下代码来获取它:

Stream res = Resources.OpenRawResource(Resource.Raw.dictionary);
MemoryStream ms = new MemoryStream();
res.CopyTo(ms);
ms.Position = 0;
StreamReader stream = new StreamReader(ms, Encoding.UTF8, true);

有没有更好的方法从资源文件中获取可用的StreamReader?似乎多次转换和复制流可能会使代码变慢。

【问题讨论】:

  • 您好,看来您的共享代码是不错的解决方案,否则您可以使用 Android Assets 来获取 StreamReader。

标签: android xamarin xamarin.android


【解决方案1】:

您可以使用 using 语句。 试试这个代码:

try{
   var _file = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "dictionary.txt");

   if(_file == null || !File.Exists(_file)){
      //file does not exist
   }
   
   string FileData = string.Empty;
   using(var reader = new StreamReader(_file, true)){
      string line;
      while((line = reader.ReadLine()) != null)
      {
         FileData = line;
      }
   }

   //

}catch(Exception ex){
 //Exception error
}

【讨论】:

  • 对我来说System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "dictionary.txt" 不存在。
  • 您可以使用 "Xamarin.Essentials" // 获取内部存储文件的路径 _file = Path.Combine(Xamarin.Essentials.FileSystem.AppDataDirectory, "dictionary.txt"); // 获取缓存目录中文件的路径 _file = Path.Combine(Xamarin.Essentials.FileSystem.CacheDirectory, "dictionary.txt");
【解决方案2】:

您需要将您的文件标记为 AndroidAsset:

然后是的,您可以使用类似于此代码的内容:

AssetManager assets = ApplicationContext.Assets;
Stream stream = assets.Open(ConfigurationFilePath);
// Play with the stream and dispose it.

我在一篇旧文章中解释了类似的内容:Xamarin - Loading configuration file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多