从文本文件读取的Xamarin表单结果为空 [英] Xamarin Forms Read From Text File Result is Null

查看:120
本文介绍了从文本文件读取的Xamarin表单结果为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目文件浏览器中有data.txt文件.我想从该文本文件中读取数据,但是每次尝试时,结果都为空,并且程序崩溃.我写的代码是:

I have data.txt file in my project file explorer. I want to read data from this text file, but every time I try it, the result comes null and the program crashes. The code I wrote is :

public MapPage()
{
    var assembly = typeof(MapPage).GetTypeInfo().Assembly;
    Stream stream = assembly.GetManifestResourceStream("Mapper.data.txt");

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

使用此代码块,流始终为空.这是项目文件浏览器:

Using this code block, the stream always comes null. Here is the project file explorer :

我从其属性中选择文本文件作为嵌入式资源".

I select the text file as Embedded Resource from its properties.

推荐答案

我终于找到了解决方案.这不是解决它的好方法,但它可以工作.我的问题是给出文本文件的路径不起作用.该程序无法读取文本文件.但是,使用此代码,程序本身会找到文本文件的路径并使用它.

I've finally found the solution. It is not a good way to solve it but it works. My problem was giving the path of the text file wasn't working. The program couldn't read the text file. But using this code, the program itself finds the path of the text file and uses it.

private void LoadData()
{
    var assembly = typeof(MapPage).GetTypeInfo().Assembly;
    foreach (var res in assembly.GetManifestResourceNames())
    {
        if(res.Contains("data.txt"))
        {
            Stream stream = assembly.GetManifestResourceStream(res);

            using (var reader = new StreamReader(stream))
            {
                string data = "";
                while((data = reader.ReadLine()) != null)
                {        
                    var array = data.Split(' ');
                    dataArray.Add(new SensorModel()
                    {
                        left = Convert.ToInt32(array[0]),
                        right = Convert.ToInt32(array[1]),
                        front = Convert.ToInt32(array[2])
                    });
                }
            }
        }
    }
}

这篇关于从文本文件读取的Xamarin表单结果为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆