如何从SaveFileDialog获取完整路径并在“startInfo.Arguments”中使用?

12

在我的情况下,SaveFileDialog 不会写入任何文件,但我想使用它来指定一个命令行应用程序的路径,该应用程序将在与 sf 对话框中 "保存" 相同的位置创建日志文件。

SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "*.txt";
string sfdname = saveFileDialog1.FileName;
if (sfd.ShowDialog() == DialogResult.OK)
{
  Path.GetFileName(sfd.FileName);
}

startInfo.Arguments = "--log=" + Path.GetFileName(sfd.FileName);
6个回答

16

您可以使用

Path.GetFullPath(sfd.FileName);

不是...而是

Path.GetFileName(sfd.FileName);

完整版本...

SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "*.txt";
string sfdname = saveFileDialog1.FileName;
if (sfd.ShowDialog() == DialogResult.OK)
{
  Path.GetFullPath(sfd.FileName);
}

startInfo.Arguments = "--log=" + Path.GetFullPath(sfd.FileName);

6

只需删除 Path.GetFileName 即可:

startInfo.Arguments = "--log=\"" + sfd.FileName + "\"";

使用這個方法,我可以得到文件的完整路徑(我通過文本框進行了檢查),但命令行應用程序無法識別它。 - user830054
@user830054:尝试在路径周围添加引号。请参见更新的答案。 - Daniel Hilgarth

2
我认为根据您所描述的情况,您正在使用错误的对话框表格。
请尝试使用FolderBrowserDialog类:
string folderPath = string.Empty;

using (FolderBrowserDialog fdb = new FolderBrowserDialog()) {
  if (fdb.ShowDialog() == DialogResult.OK ){
    folderPath = fdb.SelectedPath;
  }
}

if (folderPath != string.Empty) {
  startInfo.Arguments = "--log=" + folderPath;
}

2
OpenFileDialog openFileDialog1 = new OpenFileDialog();
                openFileDialog1.Filter = "Image files | *.jpg";
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                 employee_dp.Image = Image.FromFile(openFileDialog1.FileName);
                 string path = System.IO.Path.GetDirectoryName(openFileDialog1.FileName);
                 string onlyFileName = System.IO.Path.GetFileName(openFileDialog1.FileName);
                 filepath = Path.GetFullPath(path).Replace(@"\", @"\\");
                 filepath = filepath + "\\\\" + onlyFileName;
                 MessageBox.Show(filepath);

那个 * 是什么意思? - Maciej Jureczko
抱歉,打错字了,呵呵。 - royhette agapito

0
问题可能是使用了错误的FileSaveDialog
Win32.dll中的那个不提供完整路径,但在System.Windows.Forms中的那个会提供。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接