0

i have the following code. i need to do this:

public void Window1()
{
   InitializeComponent();
   opendirectory();
}

public void opendirectory()
{
    Stream checkStream = null;
    Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();

     openFileDialog.Multiselect = false;    

     if ((bool)openFileDialog.ShowDialog())
     {
          try
          {
                if ((checkStream = openFileDialog.OpenFile()) != null)
                {
                    // i need the following code to be stored as a string
                    string antcbatchlocation = openFileDialog.FileName;                   
                }
           }
           catch (Exception ex)
                {
                        System.Windows.MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
            else 
            {
                System.Windows.MessageBox.Show("Problem occured, try again later");
            }
        }

then i will use that string in a later button event:

public void BuildButton_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process runantc = new System.Diagnostics.Process();

            runantc.StartInfo.FileName = antcbatchlocation;
        }

Perhaps something is wrong with this string as a variable. Seems to be like string antcbatchlocation is declared local variable. If so how should i go about fixing it? Please help thanks!

2 Answers 2

1

You should declare your string as a private member of your Window1 class, rather than a local variable in your opendirectory method. Then, in your button click method, simply check to make sure your string is not null, so you know the user has gone through your dialog and selected a file first.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to use an instance variable. That means that it's a variable that is local to the class instance (in this case `Window1). This also means that it's accessible to any method inside that class instance.

Add this line of code in your class declreation, just above the public Window1(){} constructor.

private string _BatchLocation;

then inside the opendirectory() method, instead of creating a local string variable, set the openFileDialog.FileName to this instance variable.

_BatchLocation = openFileDialog.FileName;

you can then access this in the click event handler... thus your code will look like this:

runantc.StartInfo.FileName = _BatchLocation;

Have a look at this post for more information: http://www.codeguru.com/csharp/csharp/cs_syntax/anandctutorials/article.php/c5829

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.