Process start from two strings
-
28-10-2019 - |
سؤال
I am trying to open a file which a user can set. In other words it will never be a set path or file. so when the user has selected the file they want to open this button below will open it. I have declared l1 and p1 as public strings.
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);
}
So just to review I want to open up the file just using the directory path and filename. Is this possible? I can just have p1 there and it will open an explorer showing me that directory. Thank you for looking.
المحلول
Yes it will work, but I would recommend you update your code this instead:
var path = Path.Combine(p1, l1);
Process.Start(path);
نصائح أخرى
You shouldn't use string concatenation to combine a directory and filename. In your case the resulting string will look like this:
C:\documents and settings\documentsfilename
^^
this is wrong
Instead use Path.Combine
.
string path = Path.Combine(p1, l1);
Process.Start(path);
Why don't you simply do this: -
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);
}
لا تنتمي إلى StackOverflow