csnoob
csnoob

Reputation: 73

Getting a .txt path and writing/reading in/from it

Im making a WinForm in order to get a .txt path from the user with the use of the "Find File" button, print it in the textBox and then be able to read/write into that .txt file . I cant find a possible way of making this idea possible and i always get errors in the code . Window : http://prntscr.com/9i46ch . Latest code I've tried :

        OpenFileDialog openFD = new OpenFileDialog();
        openFD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

        string path = Path.GetFileName(openFD.FileName);
        FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
        StreamWriter str = new StreamWriter(fs);

     if (openFD.ShowDialog() == DialogResult.OK)
        {
            try {
                textpathTB.Text = path;

                str.Write("Hello!");

                    }

            catch (Exception e)
            {
                MessageBox.Show("The path was not correct! Original error:" + e.Message);

            }

Upvotes: 1

Views: 206

Answers (3)

Andrey Tretyak
Andrey Tretyak

Reputation: 3231

You should open stream when you already have path, before calling openFD.ShowDialog() property FileName does not contain file path.

Beside that I think creating of FileStream in redundant in this case, you can just pass path as parameter to StreamWriter constructor, FileStream will be created inside StreamWriter constructor.

Also you should always put disposable objects (such as StreamWriter) inside using block or call Dispose() method manually.

So my variant of this function will be something like this:

    OpenFileDialog openFD = new OpenFileDialog();
    openFD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

    if (openFD.ShowDialog() == DialogResult.OK)
    {
        try 
        {
            string path = Path.GetFileName(openFD.FileName);
            textpathTB.Text = path;
            using(var str = new StreamWriter(openFD.FileName))
            {
                str.Write("Hello!");
            }
        }
        catch (Exception e)
        {
            MessageBox.Show("The path was not correct! Original error:" + e.Message);
        }
    }

Another small mistake in your solution is that you call function Path.GetFileName before passing value to stream. This function extracts file name from path, for example it will return test.txt for value C:\My Folder\test.txt. FileStream will not be able to find file base on only name without full path if it's not located in application folder.

Upvotes: 2

Valentin
Valentin

Reputation: 5488

You should get path after you show open file dialog ShowDialog ()

     OpenFileDialog openFD = new OpenFileDialog();
        openFD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

     if (openFD.ShowDialog() == DialogResult.OK)
        {
            try 
            {
                string path = Path.GetFileName(openFD.FileName);
                textpathTB.Text = path;

                using(var str = new StreamWriter(openFD.FileName))
                {
                      str.Write("Hello!");
                }

            }

            catch (Exception e)
            {
                MessageBox.Show("The path was not correct! Original error:" + e.Message);

            }
     }

Upvotes: 1

robaudas
robaudas

Reputation: 1648

Placed your code in a fresh Winforms Application and this error gets raised creating the file stream object:

"Empty path name is not legal."

You are creating the filestream object before you get the file path.
It'll help if you structure the code into the steps you are taking to accomplish the goal.

    private void CreateFileButton_Click(object sender, EventArgs e)
    {
        // Open a dialog to get the filepath

        // If the user clicked ok

            // Try to write out to the file

            // Handle exceptions
    }

It'll also benefit to put your stream objects inside using constructs so they don't hold onto the files longer than they have to.

    private void CreateFileButton_Click(object sender, EventArgs e)
    {
        OpenFileDialog openFD = new OpenFileDialog();
        openFD.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";

        if (openFD.ShowDialog() == DialogResult.OK)
        {
            try
            {
                string path = Path.GetFileName(openFD.FileName);
                using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
                {
                    using (StreamWriter str = new StreamWriter(fs))
                    {
                        textpathTB.Text = path;
                        str.Write("Hello!");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("The path was not correct! Original error:" + ex.Message);
            }
        }
    }

Upvotes: 1

Related Questions