【问题标题】:How to store the text in a string variable from a text file in the asset directory?如何将文本存储在资产目录中文本文件中的字符串变量中?
【发布时间】:2019-12-09 15:23:53
【问题描述】:

我正在用 xamarin android 做一些测试。我在资产文件夹中有一个文本文件,我知道如何访问该文件:

using (Stream myFile= Assets.Open("myFile.txt"))
{
    using (FileStream myDestinationFile= File.Create("myDestinationPath"))
    {
        myFile.CopyTo(myDestinationFile);
    }
}

使用此代码,我可以将文件复制到另一个位置,例如“个人”,因此我可以编辑该文件,因为我知道我无法编辑资产文件夹中的文件。

但我想将文本文件的信息直接传递给字符串变量,因为我不需要编辑文件,只需访问信息并将此字符串作为方法的参数传递。

可以用asset文件夹的文本文件信息设置字符串变量吗?

谢谢。

【问题讨论】:

    标签: xamarin.android


    【解决方案1】:

    但我想将文本文件的信息直接传递给字符串变量,因为我不需要编辑文件,只需访问信息并将此字符串作为方法的参数传递。

    如果你想从 Assect 文件夹的文本文件中传递字符串,你可以使用AssetManager

    文本文件:

    将 Build Action 设置为 AndroidAssect:

    代码:

    // Create a new TextView and set it as our view
            TextView tv = new TextView(this);
    
            // Read the contents of our asset
            string content;
            AssetManager assets = this.Assets;
            using (StreamReader sr = new StreamReader(assets.Open("TextFile1.txt")))
            {
                content = sr.ReadToEnd();
            }
    
            // Set TextView.Text to our asset content
            tv.Text = content;
    
    
            SetContentView(tv);
    

    结果:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-22
      • 2011-09-07
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-22
      相关资源
      最近更新 更多