UWP 10 C#.将文本文件读入列表<> [英] UWP 10 C#. Reading a text file into a List<>

查看:28
本文介绍了UWP 10 C#.将文本文件读入列表<>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先让我说我是 UWP 的新手,我最接近这种语言的是大约 12 年前的 C++!

我正在为 Windows Universal 编写一个应用程序,我将在其中逐行读取不同的文本文件,拆分每一行的内容(有些文件我不需要拆分行),添加数据放入一个列表,然后显示在屏幕上.我已经尝试了很多方法来做到这一点,但我没有让它正常工作.我目前有两种有效的方法,但不一致.它会显示数据,但只是有时.当我运行应用程序(在模拟器中或在本地设备上)时,它可能会或可能不会显示数据,然后如果我点击不同的页面并返回列表页面,它可能会也可能不会再次显示.

这是代码..在这种情况下,我将文本文件的内容拆分为 3 个字符串,并以-"分隔

在我的 XAML.cs 文件中

公共密封分部类 SPList : Page{私有列表三列列表;公共 SPList(){this.InitializeComponent();ThreeColumnLists = ThreeColumnListManager.GetList();}}

在我的 XAML 中

<页面资源><!-- x:DataType="<类名>"--><DataTemplate x:Key="ThreeColumnListDataTemplate" x:DataType="data:ThreeColumnList"><StackPanel Orientation="Horizo​​ntal" Horizo​​ntalAlignment="Left"><TextBlock Grid.Column="0" Text="{x:Bind Name}" Horizo​​ntalAlignment="Left" FontSize="16" Margin="20,20,20,20"/><TextBlock Grid.Column="1" Text="{x:Bind Age}" Horizo​​ntalAlignment="Left" FontSize="16" Margin="20,20,20,20"/><TextBlock Grid.Column="2" Text="{x:Bind Job}" Horizo​​ntalAlignment="Right" FontSize="16" Margin="20,20,20,20"/></StackPanel></数据模板></Page.Resources><Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"><Grid.RowDefinitions><RowDefinition Height="*"/><RowDefinition Height="100"/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="2*"/><ColumnDefinition Width="*"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions><TextBlock Grid.Row="1"名称="结果文本块"字体大小=24"前景=红色"字重=粗体"保证金="20,20,0,0"/><!-- ItemsSource="x:Bind <来自 CS(Code) 类的变量> --><ListView Grid.ColumnSpan="3" ItemsSource="{x:Bind ThreeColumnLists}"ItemTemplate="{StaticResource ThreeColumnListDataTemplate}"></ListView></网格></页面>

在 ThreeColumnList.cs 中

class ThreeColumnList{公共字符串名称{获取;放;}公共字符串年龄{得到;放;}公共字符串作业 { 获取;放;}}

在我的 ThreeColumnListManager.cs 中

class ThreeColumnListManager{公共静态列表获取列表(){var threecolumnlists = new List();//添加一个虚拟行以在屏幕上呈现一些东西Threecolumnlists.Add(new ThreeColumnList { Name = "Name1", Age = "Age1", Job = "Job1" });//第一种工作方法读取列表(三列列表);//第二种工作方法//再次尝试(三列列表);返回三个列列表;}public static async void readList(List tcl){列表<三列列表>a = tcl;字符串_行;var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Lists/splist.txt"));使用 (var inputStream = await file.OpenReadAsync())使用 (var classicStream = inputStream.AsStreamForRead())使用 (var streamReader = new StreamReader(classicStream)){而 (streamReader.Peek() >= 0){Debug.WriteLine("行");_line = streamReader.ReadLine();//Debug.WriteLine(string.Format("the line is {0}", _line ));string _first = "" + _line.Split('-')[0];string _second = "" + _line.Split('-')[1];string _third = "" + _line.Split('-')[2];a.Add(new ThreeColumnList { Name = _first, Age = _second, Job = _third });}}}public static async void tryAgain(List tcl){//加载文件夹var _folder = Windows.ApplicationModel.Package.Current.InstalledLocation;_folder = await _folder.GetFolderAsync("Lists");//获取文件var _file = await _folder.GetFileAsync("splist.txt");//读取内容IList<字符串>_ReadLines = 等待 Windows.Storage.FileIO.ReadLinesAsync(_file);int i = 0;foreach (var _line in _ReadLines){我++;string _first = "" + _line.Split('-')[0];string _second = "" + _line.Split('-')[1];string _third = "" + _line.Split('-')[2];tcl.Add(new ThreeColumnList { Name = _first, Age = _second, Job = _third });}Debug.WriteLine("计数为" + i);}}

在这种情况下,文件被分成三部分,文本文件的样本看起来像这样

博客,Joe-25-Engineer弗林,约翰-43 助理警长,Patsy-54-经理!-!-!

这条线!-!-!是一个分隔线,但它仍然会显示!!!拆分后在屏幕上 -

最初我试图获取文件的内容并将它们返回给 GetList() 并将内容处理到列表中,但我没有运气.

然后我决定尝试将列表传递给获取内容并在那里填充列表的方法.

我拥有的两个功能都将内容显示到屏幕上,但不一致.ReadList() 似乎比 tryAgain() 更频繁地工作,但它仍然不是每次都有效.

另外,请注意,我已经尝试过,我没有拆分文件每一行的内容,而且我看到了同样的问题,它只会偶尔加载.

Let me start by saying that I'm brand new to UWP and the closest I have come to this language would be C++ about 12 years ago!

I'm writing an app for Windows Universal and in it I'll be reading different text files in line by line, split the contents of each line (Some files I won't need to split the line), add the data into a list and then show it on screen. I've tried many ways to do this but I haven't got it working correctly. I currently have two methods that are working, but not consistently. It will show the data but only sometimes. When I run the app (either in emulator or on local device) it may or may not show the data and then if I click to a different page and back into the list page, it may or may not show it again..

Here's the code.. In this case I'm splitting the contents of the text file into 3 strings splitting on a '-'

in my XAML.cs file

public sealed partial class SPList : Page
{
    private List<ThreeColumnList> ThreeColumnLists;
    public SPList()
    {
        this.InitializeComponent();
        ThreeColumnLists = ThreeColumnListManager.GetList();
    }
}

in my XAML

<Page
    x:Class="TrackingAssistant.SPList"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TrackingAssistant"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:data="using:TrackingAssistant.Model"
    mc:Ignorable="d">
    <Page.Resources>
        <!-- x:DataType="<Name Of Class>" -->
        <DataTemplate x:Key="ThreeColumnListDataTemplate" x:DataType="data:ThreeColumnList">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
                <TextBlock Grid.Column="0" Text="{x:Bind Name}" HorizontalAlignment="Left" FontSize="16" Margin="20,20,20,20" />
                <TextBlock Grid.Column="1" Text="{x:Bind Age}" HorizontalAlignment="Left" FontSize="16" Margin="20,20,20,20" />
                <TextBlock Grid.Column="2" Text="{x:Bind Job}" HorizontalAlignment="Right" FontSize="16" Margin="20,20,20,20" />
            </StackPanel>
        </DataTemplate>
    </Page.Resources>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="100" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2*" />
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />

        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row="1" 
                   Name="ResultTextBlock" 
                   FontSize="24" 
                   Foreground="Red" 
                   FontWeight="Bold" 
                   Margin="20,20,0,0" />
        <!--  ItemsSource="x:Bind <Variable from the CS(Code) Class>   -->
        <ListView Grid.ColumnSpan="3" ItemsSource="{x:Bind ThreeColumnLists}" 
                  ItemTemplate="{StaticResource ThreeColumnListDataTemplate}">
        </ListView>

    </Grid>
</Page>

in ThreeColumnList.cs

class ThreeColumnList
{
    public string Name { get; set; }
    public string Age { get; set; }
    public string Job { get; set; }
}

In my ThreeColumnListManager.cs

class ThreeColumnListManager
{
    public static List<ThreeColumnList> GetList()
    {
        var threecolumnlists = new List<ThreeColumnList>();

        //Add a dummy row to present something on screen
        threecolumnlists.Add(new ThreeColumnList { Name = "Name1", Age = "Age1", Job = "Job1" });

        //First working method
        readList(threecolumnlists);

        //Second Working Method
        //tryAgain(threecolumnlists);

        return threecolumnlists;
    }

    public static async void readList(List<ThreeColumnList> tcl)
    {
        List<ThreeColumnList> a = tcl;
        string _line;
        var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Lists/splist.txt"));
        using (var inputStream = await file.OpenReadAsync())
        using (var classicStream = inputStream.AsStreamForRead())
        using (var streamReader = new StreamReader(classicStream))
        {
            while (streamReader.Peek() >= 0)
            {
                Debug.WriteLine("Line");
                _line = streamReader.ReadLine();
                //Debug.WriteLine(string.Format("the line is {0}", _line ));
                string _first = "" + _line.Split('-')[0];
                string _second = "" + _line.Split('-')[1];
                string _third = "" + _line.Split('-')[2];

                a.Add(new ThreeColumnList { Name = _first, Age = _second, Job = _third });
            }
        }
    }

    public static async void tryAgain(List<ThreeColumnList> tcl)
    {
        //Loading Folder
        var _folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
        _folder = await _folder.GetFolderAsync("Lists");

        //Get the file
        var _file = await _folder.GetFileAsync("splist.txt");

        // read content
        IList<string> _ReadLines = await Windows.Storage.FileIO.ReadLinesAsync(_file);

        int i = 0;
        foreach (var _line in _ReadLines)
        {
            i++;
            string _first = "" + _line.Split('-')[0];
            string _second = "" + _line.Split('-')[1];
            string _third = "" + _line.Split('-')[2];
            tcl.Add(new ThreeColumnList { Name = _first, Age = _second, Job = _third });
        }
        Debug.WriteLine("Count is " + i);
    }
}

And in this case with the file being split into three, a sample of the text file would look like this

Bloggs, Joe-25-Engineer
Flynn, John-43-Assistant
Sherriff, Patsy-54-Manager
!-!-!

The line !-!-! is a seperator line but it will still display ! ! ! on screen after splitting on the -

Initially I was trying to grab the contents of the file and return them to GetList() and process the contents into the List there but I was having no luck.

Then I decided to try pass the list to the method that grabs the content and populate the List there.

Both the functions I have do display content to the screen but not consistently. ReadList() seems to work more frequently that tryAgain() but it still does not work every time.

Also, just to note, I've tried this where I'm not splitting the contents of each line of the file and I'm seeing the same issue where it will load only sometimes.

I was following this video to get the initial list working. Once I got this working then I moved onto reading in from file.

I have a feeling that I'm really close but I'm not sure.

Anyone any advice on where I'm going wrong?

Thanks!

解决方案

Try implementing INotifyPropertyChanged and ObservableCollection interfaces that are used to notify clients, typically binding clients, that a property value has changed.

Also use Task to load the data.

Edit:

MainPage.cs.xaml

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Net.Sockets;
using System.Threading.Tasks;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace TestUWP
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        private ObservableCollection<ThreeColumnList> threeColumnLists;

        public ObservableCollection<ThreeColumnList> ThreeColumnLists
        {
            get { return threeColumnLists ?? (threeColumnLists = new ObservableCollection<ThreeColumnList>()); }
            set { threeColumnLists = value; }
        }
        public MainPage()
        {
            this.InitializeComponent();
            LoadData();

        }

        private async void LoadData()
        {
            //you can also change the private threeColumnLists to a static 
            // and do 
            //if(ThreeColumnLists.Count==0) 
            //   ThreeColumnLists = await ThreeColumnListManager.GetListAsync();
            ThreeColumnLists = await ThreeColumnListManager.GetListAsync();
            //can also do
            // await ThreeColumnListManager.readList(ThreeColumnLists);
        }

    }

    public class ThreeColumnList : INotifyPropertyChanged
    {
        private string name = string.Empty;
        public string Name { get { return name; } set { name = value; NotifyPropertyChanged("Name"); } }

        private string age = string.Empty;
        public string Age { get { return age; } set { age = value; NotifyPropertyChanged("Age"); } }

        private string job = string.Empty;
        public string Job { get { return job; } set { job = value; NotifyPropertyChanged("Job"); } }

        //PropertyChanged handers
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,
                    new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    public class ThreeColumnListManager
    {
        public static async Task<ObservableCollection<ThreeColumnList>> GetListAsync()
        {
            var threecolumnlists = new ObservableCollection<ThreeColumnList>();

            //Add a dummy row to present something on screen
            threecolumnlists.Add(new ThreeColumnList { Name = "Name1", Age = "Age1", Job = "Job1" });

            //First working method
            await readList(threecolumnlists);

            //Second Working Method
            //tryAgain(threecolumnlists);

            return threecolumnlists;
        }

        public static async Task readList(ObservableCollection<ThreeColumnList> tcl)
        {
            string _line;
            var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Lists/slplist.txt"));
            using (var inputStream = await file.OpenReadAsync())
            using (var classicStream = inputStream.AsStreamForRead())
            using (var streamReader = new StreamReader(classicStream))
            {
                while (streamReader.Peek() >= 0)
                {
                    Debug.WriteLine("Line");
                    _line = streamReader.ReadLine();
                    //Debug.WriteLine(string.Format("the line is {0}", _line ));
                    string _first = "" + _line.Split('-')[0];
                    string _second = "" + _line.Split('-')[1];
                    string _third = "" + _line.Split('-')[2];

                    tcl.Add(new ThreeColumnList { Name = _first, Age = _second, Job = _third });
                }
            }
        }

        public static async Task tryAgain(ObservableCollection<ThreeColumnList> tcl)
        {
            //Loading Folder
            var _folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            _folder = await _folder.GetFolderAsync("Lists");

            //Get the file
            var _file = await _folder.GetFileAsync("splist.txt");

            // read content
            IList<string> _ReadLines = await Windows.Storage.FileIO.ReadLinesAsync(_file);

            int i = 0;
            foreach (var _line in _ReadLines)
            {
                i++;
                string _first = "" + _line.Split('-')[0];
                string _second = "" + _line.Split('-')[1];
                string _third = "" + _line.Split('-')[2];
                tcl.Add(new ThreeColumnList { Name = _first, Age = _second, Job = _third });
            }
            Debug.WriteLine("Count is " + i);
        }
    }
}

MainPage.xaml

<Page
x:Class="TestUWP.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TestUWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">

<Page.Resources>
    <!-- x:DataType="<Name Of Class>" -->
    <DataTemplate x:Key="ThreeColumnListDataTemplate" x:DataType="local:ThreeColumnList">
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
            <TextBlock Grid.Column="0" Text="{x:Bind Name}" HorizontalAlignment="Left" FontSize="16" Margin="20,20,20,20" />
            <TextBlock Grid.Column="1" Text="{x:Bind Age}" HorizontalAlignment="Left" FontSize="16" Margin="20,20,20,20" />
            <TextBlock Grid.Column="2" Text="{x:Bind Job}" HorizontalAlignment="Right" FontSize="16" Margin="20,20,20,20" />
        </StackPanel>
    </DataTemplate>
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="100" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*" />
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />

    </Grid.ColumnDefinitions>
    <TextBlock Grid.Row="1" 
               Name="ResultTextBlock" 
               FontSize="24" 
               Foreground="Red" 
               FontWeight="Bold" 
               Margin="20,20,0,0" />
    <!--  ItemsSource="x:Bind <Variable from the CS(Code) Class>   -->
    <ListView Grid.ColumnSpan="3" ItemsSource="{x:Bind ThreeColumnLists}" 
              ItemTemplate="{StaticResource ThreeColumnListDataTemplate}">
    </ListView>

</Grid>

Output:

这篇关于UWP 10 C#.将文本文件读入列表&lt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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