user3734454
user3734454

Reputation: 59

using open file dialog box on a windows form

I wrote a program which reads a csv file, makes some changes and writes to a new csv file.

I want the user to be able to select the csv file to be read from their directory using an open file dialog box on a windows form.

So far I have been able to write some of the code so that the user can look for the file but I am not sure on how to link the file the user has chosen to the steamreader.

This is the code to read and write the csv file

try 
{
    using (StreamWriter sw = new StreamWriter("X:/PublishedSoftware/Data/NEWPYAEGON1PENSION.csv"))
    {
        using (StreamReader sr = new StreamReader(""))
        {

This is the code for the open file dialog box

private void btnFindAegonFile_Click(object sender, EventArgs e)
{
    openFileDialog1.Filter = "csv files(*.csv)|*.csv|All files(*.*)|*.*";
    openFileDialog1.FileName = "Browse for the AEGON file.";

    DialogResult result = openFileDialog1.ShowDialog();

    txtFindAegonFile.Text = this.openFileDialog1.FileName;

Upvotes: 0

Views: 4260

Answers (5)

user3734454
user3734454

Reputation: 59

I got it working I used:

string readfilename = txtFindAegonFile.Text;

try
{
    using (StreamReader sr = new StreamReader(readfilename))
    using (StreamWriter sw = new StreamWriter("X:/PublishedSoftware/Data/NEWPYAEGON1PENSION.csv"))
}

Upvotes: 0

Austinh100
Austinh100

Reputation: 598

Use openFileDialog1's FileOK event to know when the user has selected a valid file. You can then recive the file path from openFileDialog1.FileName.

Upvotes: 0

Alexander Bell
Alexander Bell

Reputation: 7918

You have to complete the FileOpen Dialog code snippet by passing the file path to StreamWriter, like:

  using (StreamWriter sw = new StreamWriter(fileName));
  // ... open the file w/StreaWriter

Upvotes: 0

Eric Scherrer
Eric Scherrer

Reputation: 3388

Here is a snippet of how to go from a file name to a StreamReader:

var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (var sr = new StreamReader(fs))
{
...
}

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 156978

If you have the file name:

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    string fileName = this.openFileDialog1.FileName;

    ...
}

You can read the contents using the stream reader (in the place of ...):

using (StreamReader sr = new StreamReader(fileName))

Or read the contents directly:

string input = File.ReadAllText(fileName);

Upvotes: 3

Related Questions