1

I want to make a button that

  • opens a file from some location in file system,
  • gets its file path,
  • pass the file path like an argument to a method
  • open that file and do something with it.

I've made a button like this:

private void button1_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fDialog = new OpenFileDialog();

            fDialog.Title = "Open XML file";
            fDialog.Filter = "XML files|*.config";
            fDialog.InitialDirectory = @"C:\";
            fDialog.ShowDialog();
        }

I already made a method that reads from hard-coded location, but can someone help me about that file path part variable?

Method reads file with XmlTextReader like this:

private void ReadAdvancedConfigFile()
        {
            XElement root = null;
            root = XElement.Load(new XmlTextReader(@"C:\Users\nemanja.mosorinski\Downloads\__Research-master\__Research-master\SEDMSVSPackage\VisualStudioPackage\AppRes\ConfigFiles\Unity.config"));
        }

So basically I want to put new file path for some file founded by OpenFileDialog in root variable.

1
  • Why do you initialize the variable to null? Commented Feb 4, 2014 at 8:43

1 Answer 1

2

Change this line:

fDialog.ShowDialog();

To:

bool? control = fDialog.ShowDialog();
if(control.Value)
{
   var filePath = fDialog.FileName;
   ReadAdvancedConfigFile(filePath)
}

Also you should change the method signature

private void ReadAdvancedConfigFile(string path)
Sign up to request clarification or add additional context in comments.

8 Comments

I got an error for DialogResult.OK. It says that 'System.Nullable<null>' does not contain a definition for 'OK'.
@nemo_87 use this: System.Windows.Forms.DialogResult.OK
Now it says: Error 1 Operator '==' cannot be applied to operands of type 'bool?' and 'System.Windows.Forms.DialogResult'
You didn't add OK System.Windows.Forms.DialogResult.OK
@nemo_87 You have to actually read the error messages and try to understand them. Don't just give up as soon as you see an error. The errors all have meaning and they all explain what the problem is.
|

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.