流读取器(从.txt文件中提取数据以显示在listBox中)

时间:2015-05-06 08:07:07

标签: c# streamreader streamwriter

我有一个.txt文件,在 form2 中,我正在写信。我现在需要调用.txt文件,然后将每行字符显示在 form3 上的listBox中。但我收到了错误。

  

错误1:'string'不包含'Add'的定义,也没有扩展方法'Add'接受'string'类型的第一个参数   可以找到(你错过了使用指令或程序集   引用?)

     

错误2:无法将方法组“ReadLine”转换为非委托类型“string”。你打算调用这个方法吗?

旁注该文件名为“ data.txt ”,表单3名为“统计信息”。

public partial class Stats : Form
{
    public Stats()
    {
        InitializeComponent();
    }

    private void Stats_Load(object sender, EventArgs e)
    {
        StreamReader StreamIn = File.OpenText(@"data.txt");
        string Record = StreamIn.ReadLine();

        while (Record != null)
        {
            listBox1.Text.Add(Record);
            Record = StreamIn.ReadLine;
        }
        StreamIn.Close();
    }
}

7 个答案:

答案 0 :(得分:4)

listBox1.Text的类型为stringString没有Add功能。属性Text表示所选项目,而不是项目集合。您可以向Items属性添加项目,如下所示:

listBox1.Items.Add(Record);

其次,所有方法必须以(零个或多个参数和)结尾:

Record = StreamIn.ReadLine();

您可以在读取记录的代码行中正确执行此操作。

*编辑(在Dmitry Bychenko的评论之后)*

另一种更快的方法是:

private void Stats_Load(object sender, EventArgs e)
{
    listBox1.Items.AddRange(File.ReadAllLines(@"data.txt"));
}

答案 1 :(得分:1)

为什么不简单

listBox1.Text = File.ReadAllText(@"data.txt");

没有任何Stream s(应该被using生效)?或

listBox1.Items.AddRange(File.ReadAllLines(@"data.txt"));

Stream实施可能是这样的:

   using (StreamReader StreamIn = File.OpenText(@"data.txt")) { // <- using!
     for (String Record = StreamIn.ReadLine(); Record != null; Record = StreamIn.ReadLine()) {
       listBox1.Items.Add(Record);
     }
   }

答案 2 :(得分:0)

应该是:

listBox1.Items.Add(Record)

答案 3 :(得分:0)

您需要使用,

.Add()

List函数是集合中的函数,即IEnumerablelistBox1.Items.Add(Record); 等。您不能在字符串中使用它。

或许,您想要添加新项目?

[HttpPost]
public ActionResult CreateSomething([ModelBinder(typeof(MyCustomModelBinder))] Something something) 
{

}

public class MyCustomModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        // Do something
        return base.BindModel(controllerContext, bindingContext);
    }
}

这可以帮到你。

答案 4 :(得分:0)

在ReadLine的末尾添加括号:

Record = StreamIn.ReadLine();

答案 5 :(得分:0)

理想情况下,您应该使用using语句。您可以使用EndOfStream而不是多条读取线

using (StreamReader StreamIn = File.OpenText(@"data.txt"))
{
   while (!StreamIn.EndOfStream)
       listBox1.Text.Add(StreamIn.ReadLine());
}

答案 6 :(得分:0)

    using (StreamReader sr = new StreamReader(@"data.txt"))
        {
            while (sr.Peek() >= 0)
            {
                listBox1.Items.Add(sr.ReadLine());
            }
        }

https://msdn.microsoft.com/it-it/library/system.io.streamreader.readline(v=vs.110).aspx

相关问题