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

本文关键字:变量 路径 文件 何使用 openfiledialog 控件 | 更新日期: 2023-09-27 18:20:42

我在这里有这样的代码,我用它来上传一些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时,我需要它;

它是什么?

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

您可能想要的是比较两个文件的内容
正如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);
}