I am working on a project with winforms. I want to read from an existing .txt file but without hard coding. This means that I want to allow the user to provide the path of the file as input. I have tried the following code:
private void pathSearch_TextChanged(object sender, EventArgs e)
{
string path = "";
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
path = ofd.FileName;
pathSearch.Text = File.ReadAllText(path);
}
string[] lines = File.ReadAllLines(path);
if (!File.Exists(path))
{
// Create a file to write to.
string[] createText = { "Hello", "And", "Welcome" };
File.WriteAllLines(path, createText);
}
string[] values;
for (int i = 0; i < lines.Length; i++)
{
values = lines[i].ToString().Split('|');
string[] row = new string[values.Length];
for (int j = 0; j < values.Length; j++)
{
row[j] = values[j].Trim();
}
table.Rows.Add(row);
}
}
You can check screenshot1 and screenshot2 to give you an idea of how it will work. I want to enter the path inside the text field but it gives me an ArgumentNullException. After entering the path I want to import by using the button to see the data on that table. P.s I'm not sure if checking the existence of the path, works that way.
Edit
After the comments I edited my code and I have something that works. However, in order to import the file I have to select it 2 times and it is writing the same lines twice inside the table. How can I fix that?