Home > Software engineering >  how to access OpenFileDialog with Streamwrite?
how to access OpenFileDialog with Streamwrite?

Time:09-06

i want to make a windows forms app with 2 buttons

1 Button to find a .wtf or .txt file

Second Button to write a line into selected file let`s say "example"

this is my first button

        private void button5_Click_1(object sender, EventArgs e)
        {
            OpenFileDialog choofdlog = new OpenFileDialog();
            choofdlog.Filter = "All Files (*.*)|*.*";
            choofdlog.FilterIndex = 1;
            choofdlog.Multiselect = false;

            if (choofdlog.ShowDialog() == DialogResult.OK)
            {
                
                string sFileName = choofdlog.FileName;                      
            }
        }

now how do i make the second button write "example" into the file i selected with the first one ?

CodePudding user response:

You can archieve this in two steps:

First, you have to store the file name in a member variable:

private string _fileName;

private void button5_Click_1(object sender, EventArgs e)
{
    OpenFileDialog choofdlog = new OpenFileDialog();
    choofdlog.Filter = "All Files (*.*)|*.*";
    choofdlog.FilterIndex = 1;
    choofdlog.Multiselect = false;

    if (choofdlog.ShowDialog() == DialogResult.OK)
    {
        _fileName = choofdlog.FileName;                      
    }
}

In the second step, you have to define the logic of button 2:

private void secondButton_Click_1(object sender, EventArgs e)
{
    System.IO.File.WriteAllText( _fileName, "Example" );
}

CodePudding user response:

"1 Button to find a .wtf or .txt file"

To look for specific file extensions you should change your filter a bit

openFileDialog.InitialDirectory = "c:\\";
    openFileDialog.Filter = "txt files (*.txt)|*.txt|wtf files (*.wtf)|*.wtf";
    openFileDialog.FilterIndex = 2;
    openFileDialog.RestoreDirectory = true;

Microsoft docs

  • Related