1

我正在尝试打开用户可以设置的文件。换句话说,它永远不会是一个设定的路径或文件。所以当用户选择了他们想要打开的文件时,下面的这个按钮将打开它。我已将 l1 和 p1 声明为公共字符串。

    public void button4_Click(object sender, EventArgs e)
    {

         DialogResult result = openFileDialog1.ShowDialog();
         if (result == DialogResult.OK)
         {

             l1 = Path.GetFileName(openFileDialog1.FileName);
             p1 = System.IO.Path.GetDirectoryName(openFileDialog1.FileName);

         }


    public void button2_Click(object sender, EventArgs e)
    {
    //p1 = directory path for example "C:\\documents and settings\documents"
    //l1 = filename

        Process.Start(p1+l1);
    }

所以只是为了查看我想只使用目录路径和文件名打开文件。这可能吗?我可以在那里有 p1 ,它会打开一个资源管理器,向我显示该目录。谢谢你的关注。

4

3 回答 3

3

是的,它会起作用,但我建议您改为更新您的代码:

var path = Path.Combine(p1, l1);
Process.Start(path);
于 2012-02-20T15:22:02.893 回答
2

您不应该使用字符串连接来组合目录和文件名。在您的情况下,生成的字符串将如下所示:

C:\documents and settings\documentsfilename
                                  ^^
                             this is wrong

而是使用Path.Combine.

string path = Path.Combine(p1, l1);
Process.Start(path);
于 2012-02-20T15:21:55.620 回答
1

你为什么不简单地这样做: -

public void button4_Click(object sender, EventArgs e)
{
    string fileNameWithPath;
    DialogResult result = openFileDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        fileNameWithPath = openFileDialog1.FileName;
    }
}

public void button2_Click(object sender, EventArgs e)
{
    Process.Start(fileNameWithPath);
}
于 2012-02-20T15:27:31.050 回答