如何使用openfiledialog控件将文件路径传递给变量?

时间:2014-09-04 13:22:17

标签: c# visual-studio

我在这里使用此代码,以便在Windows窗体中上传一些内容:

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);

}

显然我做错了,因为我没有通过我需要的tbFilePath.Text string Xml1 = tbFilePath.Text;

这是什么?

1 个答案:

答案 0 :(得分:1)

您可能想要的是比较2个文件的内容 正如siride所说,你的代码没有意义(见他的评论) 将此方法添加到您的班级

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;

}

然后你可以这样做:

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);
}