Search code examples
c#visual-studioopenfiledialog

Get one String from a Method into another Method


I'm currently writing a program and I'm very new to this topic. I've started with a program where you can select a zip file and unzip it.

For both things (selecting, unzip) I've used one button. So there is a button for selecting and one button for unzipping.

Now after selecting the file I wanna put the directory into a string, so the unzip method can unzip it.

But I don't know how to put this directory into a string. I've tried string fileDir = fdlg.FileName but this string doesn't work in the unzip method.

How can I fix this?

Select Code:

private void button2_Click(object sender, EventArgs e)
{
    OpenFileDialog fdlg = new OpenFileDialog();
    fdlg.Title = "Test - Selec ZIP File";
    fdlg.InitialDirectory = @"c:";
    fdlg.Filter = "Only ZIP Files|*.zip";
    fdlg.FilterIndex = 2;
    fdlg.RestoreDirectory = true;
    if (fdlg.ShowDialog() == DialogResult.OK)
    {
        textBox1.Text = fdlg.FileName;
    }
}

Solution

  • one possibility could be to declare a string variable on class level and NOT inside the event:

    string fileDir = "";
    
    private void button2_Click(object sender, EventArgs e)
    {
        OpenFileDialog fdlg = new OpenFileDialog();
        fdlg.Title = "Test - Selec ZIP File";
        fdlg.InitialDirectory = @"c:";
        fdlg.Filter = "Only ZIP Files|*.zip";
        fdlg.FilterIndex = 2;
        fdlg.RestoreDirectory = true;
        if (fdlg.ShowDialog() == DialogResult.OK)
        {
            textBox1.Text = fdlg.FileName;
    
            //copy here the filename
            fileDir = fdlg.FileName;
        }
    }
    

    Now you should be able to use fileDir throughout the entire class.