使用C#从文件中读取列表 [英] Reading a List from a File using C#

查看:105
本文介绍了使用C#从文件中读取列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早安专家,



如图所示:

http://s2.postimage.org/5ed0wl5tl/issue.jpg [ ^ ]



我正在尝试将列表中的数据保存到文本文件中。我正在成功恢复ti文件,但我无法从文件中读取,如图所示。我会非常感谢所有的帮助,祝你新年快乐。



谢谢:)

解决方案

问题是如果tr.readline为null,则只检查一次。在最后一项后你的文本文件中我会相信有一个空格

Saliba先生。

导致它尝试阅读下一个。



此外,tr readline将您带到下一行,所以该怎么做才能获得以下内容



循环浏览项目但跟踪索引0 - 3(如果您愿意,则为1到4)

  int  index =  0 ; 
字符串 value ;
while (( value = tr.Readline())!= null ){
if (index == 1 ){
stList [counter] .firstname = value ;
} else if // 。 。 。 。所有情况

}

index ++;

if (index == 4 ){
index = 1 ;
}

}





语法错误修复[/编辑]


当您通过调用ReadLine从文件中读取时,您从文件中取出一行文本,将其返回并前进指针。因此,当你每次绕过循环时通过读取一行并检查它是否为空来丢弃其中一行,你就会失去一步,并且没有文件。

假设你的文件包含

 Name1 
姓氏1
地址1
首选项1
名称2
姓氏
地址2
Preference2
Name3
Surname3
Address3
Preference3

循环的条目读取并丢弃Name1,然后将Surname1放入名称字段,地址1进入姓氏区域,Preference1进入地址字段,名称2进入首选项字段。



更改循环条件:

  while (tr.Peek()>  =  0 


Good Morning experts,

As shown in this image:
http://s2.postimage.org/5ed0wl5tl/issue.jpg[^]

I am trying to save the data from a list to a text file. I am successfully righting ti file, but i cannot read from the file as shown in the image. I would really apprieciate all the help and wishing you a Happy new year.

Thanks :)

解决方案

Hi the problem is you are checking only once if the tr.readline is null. in your text file after the last item I would believe there is a space
Mr Saliba.
causing it to attempt to read the next one.

Also tr readline takes you to the next line so what to do is the following

Loop through the items but keep track of the index 0 - 3 (1 to 4 if your prefer

int index = 0;
string value;
while((value = tr.Readline()) != null){
if(index == 1){
 stList[counter].firstname = value;
} else if//. . . . all the cases

}

index++;

if(index == 4){
index = 1;
}

}



[Edit]Syntax errors fixed[/Edit]


When you read from a file by calling ReadLine, you take a line of text from the file, return it, and advance the pointer. So when you discard one of those lines each time you go round the loop by reading a line and checking if it is null, you are both getting out of step, and running out of file.
Suppose your file contains

Name1
Surname1
Address1
Preference1
Name2
Surname2
Address2
Preference2
Name3
Surname3
Address3
Preference3

The entry to your loop reads and discards "Name1", then puts "Surname1" into the Name field, "Address1" into teh Surname feild, "Preference1" into the Address field, and "Name2" into the Preference field.

Change the Loop condition:

while (tr.Peek() >= 0)


这篇关于使用C#从文件中读取列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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