How to read a file and save each line at a position of a vector in C#

Asked

Viewed 81 times

0

I’m learning how to use C# in Visual Studio 2019. I want to read a text file and save each line in a position of a vector of the type string. However, when I click on "button1" to read the file and save to the vector, it gives the following error: System.Nullreferenceexception: 'Undefined object reference for an instance of an object. ' The other buttons work normally. I don’t know where I’m going wrong.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Manipular_Arquivos
{
    public partial class Editor : Form
    {
        
        int count = 0, i=0;
        string[] dados;
        public Editor()
        {
            InitializeComponent();
        }
/*É neste ponto minha dúvida. O arquivo que quero ler está da seguinte maneira:
6
7
8.3
1.0
Cada número em uma linha. Mas não consigo salvar cada linha em uma posição do vetor de string "dados"*/
        private void button1_Click(object sender, EventArgs e)
        {
            string nomeArquivo = textBox1.Text;
            StreamReader leitor = new StreamReader(nomeArquivo + ".txt");
            while (!leitor.EndOfStream)
            {
                string linha = leitor.ReadLine();
                richTextBox1.Text += linha + "\n";
                dados[count] = linha;
                count++;
            }
            leitor.Close();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string nomeArq = textBox1.Text;
            StreamWriter escritor = new StreamWriter((nomeArq + ".txt"), true);
            escritor.WriteLine(richTextBox1.Text);
            escritor.Close();
        }
        private void button5_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "";

        }

        private void button3_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = "";
            string nome = textBox1.Text;
            StreamWriter escritor = new StreamWriter(nome + ".txt");
            escritor.WriteLine("");
            escritor.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Principal novo = new Principal();
            this.Close();
            novo.Show();
            
        }

        private void button6_Click(object sender, EventArgs e)
        {
            string nomeArq = textBox1.Text;
            StreamWriter escritor = new StreamWriter(nomeArq + ".txt");
            escritor.WriteLine(richTextBox1.Text);
            escritor.Close();
        }
    }
}

1 answer

0


Because it’s not working?

Was declared a array of string, but, has not initialized the amount of positions that this array of string will, example of the declaration:

string[] dados; // não foi informado a quantidade de posições

and in this case the number of positions should be informed as follows:

string[] dados =  new string[6];

but, the problem in this statement is that the code still does not know the number of lines of the text file and this leaves the code restricted only to that amount of elements.

Solution to this problem

Use a list typical, which will be increased transparently by the code, not worrying about the amount that will come from reading this text file, example:

List<string> dados = new List<string>();

and summarizing in your code use the method Add to add to the list the lines contained in the text file:

using (StreamReader str = new StreamReader("./d.txt", System.Text.Encoding.UTF8))
{
    string line = "";
    while ((line = str.ReadLine()) != null)
    {
        dados.Add(line);
    }
}

Observing: If you have the certain number of lines that this file .txt return can use as demonstrated string[] dados = new string[6]; and in the case for assignment place dados[0] = line;, where 0 and the position of array.

  • 1

    It worked! I really didn’t know there was a way List<string>, it helped me a lot. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.