c# line by line reading txt file

100 views Asked by At
private void button1_Click(object sender, EventArgs e) //dosya seçiniz click
    {
        //OpenFileDialog file = new OpenFileDialog();
        //file.Filter = "Txt Dosyası |*.txt";
        //file.ShowDialog();

        string[] veri = new string[1000];
        StreamReader SR = new StreamReader(@"C:\Users\Murat\Pictures\New folder\DE.TXT");
        string satir;

        while (SR.ReadLine() != null)
        {
            satir = SR.ReadLine();
            veri[0] = satir;
            richTextBox1.AppendText(satir + "\n");

            richTextBox2.AppendText("{" + '"' + satir + '"' + ", new DataElement { Tag ='" + '"' + veri[0] + '"' + ", Type = FieldTypes.");
            satir = SR.ReadLine();
            richTextBox2.AppendText(satir + ", ");
            satir = SR.ReadLine();
            if (satir.Length > 3)
            {
                richTextBox2.AppendText("MinLength = 0,");
            }

hello, this my code partition, I am reading the data from line by line txt file. But how do I make array this words?

There is a Txt File. There are line-words in it. I will assign the words in this line to the array, and I will process them. But I could not create an array. And that's why I've been using the new line for many times.

2

There are 2 answers

1
Michael On

What about a single .ReadAllLines()?

EDIT:
You might use File.ReadAllLines. You pass the path of the file to read and you'll get a string-array as result. Each array element represents one line of text in the file.

But you can also continue using the StreamReader. Then you could use StreamReader.ReadToEnd. This will return a single string that contains the hole content of the text file. Then you have two choices: First you can split by CRLF to get the lines and process them as you want. Or you'll start digging into regular expressions and read this post and others about regular expressions and splitting/extracting words...

1
Sebastian L On

You should consider rewriting your "readingfunction".

use the following method as startingpoint:

public List<string> readWordsFromFile(string file) {
    list<string> result = new List<string>();
    using(Streamreader sr = new Streamreader(file)) {
        while(!sr.EndOfFile) { // making sure to read the whole file
            result.Append(sr.ReadLine().Split(" ")); // splitting words by " " (space)
        }
    }
    return result;
}

you also could do ReadToEnd().Split(" ")