how to pass file path to a variable using openfile

2019-09-07 07:42发布

问题:

I have this code here which i use in order to upload some stuff in a windows form:

public Form1()
{
    InitializeComponent();
}
private void btnLoad_Click(object sender, EventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    System.Windows.Forms.DialogResult dr = ofd.ShowDialog();
    if (dr == DialogResult.OK)
    {
        userSelectedFilePath = ofd.FileName;
    }
}

public string userSelectedFilePath
{
    get
    { return tbFilePath.Text;
    }
    set
    {tbFilePath.Text = value;
    }
}

private void btn_compare_Click(object sender, EventArgs e)
{
    string Xml1 = tbFilePath.Text;
    string Xml2 = System.IO.File.ReadAllText(@"C:");
    compare.comparison(Xml1, Xml2);

}

Apparently i'm doing something wrong because i'm not passing the tbFilePath.Text which i need when i have: string Xml1 = tbFilePath.Text;

What is it?

回答1:

What you probably want is to compare the contents of 2 files.
As siride said your code does not make sense(see his comment)
Add this method to your class

private string FindFile()
{
   OpenFileDialog ofd = new OpenFileDialog();
   string _xmlPath1 = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
   System.Windows.Forms.DialogResult dr = ofd.ShowDialog();
   if (dr == DialogResult.OK)
       return  ofd.FileName;
   else
      return null;

}

And then you can do this:

private void btn_compare_Click(object sender, EventArgs e)
{
    string x1 = System.IO.File.ReadAllText(FindFile(), Encoding.UTF8);
    string x2 = System.IO.File.ReadAllText(FindFile(), Encoding.UTF8);
    //Or if you already have the second file
    //string x2 = System.IO.File.ReadAllText(@"C:\YourPath\someFileName.xml", Encoding.UTF8);
    compare.comparison(x1, x2);
}