Reading From a Text File in C#

前端 未结 8 1659
轮回少年
轮回少年 2020-11-30 09:44

I have the following program that will send (output) information to a text file, but now I want to read (input) from the text file. Any suggestions would be greatly appreci

8条回答
  •  孤城傲影
    2020-11-30 10:15

    To read a text file one line at a time you can do like this:

    using System.IO;
    
    using (var reader = new StreamReader(fileName))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            // Do stuff with your line here, it will be called for each 
            // line of text in your file.
        }
    }
    

    There are other ways as well. For example, if the file isn't too big and you just want everything read to a single string, you can use File.ReadAllText()

    myTextBox.Text = File.ReadAllText(fileName);
    

提交回复
热议问题