sparta93
sparta93

Reputation: 3854

How to access file from another function

I'm currently working on a C# WPF application which looks something like the following. What I am trying to do is this, the first button, when pressed, basically opens up a browse dialog box where you can select multiple files. I want access to those paths inside my other button too. Ultimately I want to be able to click on the browse button, select a file and then press the second button to perform a function on the paths. Any help will be appreciated!

private void Button_Click1(object sender, RoutedEventArgs e) //BROWSE BUTTON
{
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
    dlg.Multiselect = true;
    dlg.FileName = "Document"; 
    dlg.DefaultExt = ".txt";  
    dlg.Filter = "Text documents (.txt)|*.txt"; 
    foreach (String file in dlg.FileNames)
    {
      // do something
    }
}    

private void Button_Click(object sender, RoutedEventArgs e, string p)
{
    myFunction(p);
}

Upvotes: 2

Views: 240

Answers (1)

Mike Eason
Mike Eason

Reputation: 9723

You can simply have a private variable outside of the Button_Click1 method which will hold the chosen file names.

string[] files;

private void Button_Click1(object sender, RoutedEventArgs e) //BROWSE BUTTON
{
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
    dlg.Multiselect = true;
    dlg.FileName = "Document"; 
    dlg.DefaultExt = ".txt";  
    dlg.Filter = "Text documents (.txt)|*.txt"; 

    Nullable<bool> result = dlg.ShowDialog();

    if (result == true)
        files = dlg.FileNames;
    else
    {
        //Do something useful if the user cancels the dialog
    }
} 

Then in your other method, simply reference the files variable, which will hold your array of chosen file names.

Example usage:

for (int i = 0; i < files.Length; i++)
{
    myFunction(files[i]);
}

The above code will iterate through each file in the array and call the myFunction method.

Upvotes: 3

Related Questions