【问题标题】:Can OpenFileDialog and SaveFileDialog have different InitialDirectory valuesOpenFileDialog 和 SaveFileDialog 可以有不同的 InitialDirectory 值吗
【发布时间】:2014-01-30 00:41:27
【问题描述】:

我在 Windows 窗体上有两个按钮,一个名为 Browse,另一个名为 Change Location

我希望能够为每个按钮设置不同的 InitialDirectory 值。

原因是Browse 按钮打开要在屏幕上显示的图像,Change Location 将文本文件保存到所选位置。我希望这些文件夹不同。

到目前为止,我已经提供了以下代码:

//Code for the browse button
private void browseButton_Click(object sender, EventArgs e)
{
    using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
    {
        openFileDialog1.Title = "Select Image Files To Be Displayed";
        openFileDialog1.InitialDirectory = @"..\..\pigeonImages\";
        // Set filter options and filter index.
        openFileDialog1.Filter = "Image Files|*.png;*.jpeg;*.gif|All Files|*.*";
        openFileDialog1.FilterIndex = 2;
        openFileDialog1.FileName = String.Empty;
        //Allow for multiple files to be selected
        openFileDialog1.Multiselect = true;

        // Call the ShowDialog method to show the dialog box.
        DialogResult result = openFileDialog1.ShowDialog();

        if (result == DialogResult.OK)
        {
            //Create a stream which points to the open file
            Stream openFileStream = openFileDialog1.OpenFile();
            //Create a reader
            StreamReader reader = new StreamReader(openFileStream);
            //Read the contents of the stream
            string shortenedFilenames = String.Empty;
            StringBuilder totalFiles = new StringBuilder();
            //to get just one filename use openDialog1.FileName
            //to get multiple filenames use openDialog1.FileNames
            foreach(string file in openFileDialog1.FileNames)
            {
                shortenedFilenames = file.Substring(openFileDialog1.FileName.LastIndexOf(@"\") + 1);
                totalFiles.Append(shortenedFilenames).Append(", ");
            }
            string totalFilesResult = totalFiles.ToString();
            totalFilesResult = totalFilesResult.TrimEnd(' ');
            totalFilesResult = totalFilesResult.TrimEnd(',');
            tbResults.Text = totalFilesResult;
            System.Diagnostics.Debug.WriteLine("fileStream -> " + totalFilesResult);

            //Close the reader
            reader.Close();
        }
    }
}


//Code for the Change Location button
private void saveLocationButton_Click(object sender, EventArgs e)
{
    using (SaveFileDialog saveTextDialog = new SaveFileDialog())
    {
        saveTextDialog.Title = "Save File In Correct Folder!";
        saveTextDialog.InitialDirectory = @"..\..\testScores\";

        tbSaveLocation.BackColor = Color.White;
        tbSaveLocation.ForeColor = Color.Black;

        saveTextDialog.Filter = "Text Files | *.txt";
        saveTextDialog.DefaultExt = "txt";

        saveResult = saveTextDialog.ShowDialog();


        if (saveResult == DialogResult.OK)
        {
            Stream saveFileStream = saveTextDialog.OpenFile();
            using (StreamWriter writer = new StreamWriter(saveFileStream))
            {
                writer.Write("");
                writer.Flush();
                //writer.Close();
            }
        }
        tbSaveLocation.Text = String.Format("testScores/{0}/{0}.txt", birdIdString);
    }
}

这里有什么我遗漏的吗?

我在每种方法中设置了不同的InitialDirectory 值。 我还使用了不带@symbol 的字符串,并将\'s 更改为/'s,但这仍然不起作用。

似乎无论我点击哪个按钮,pigeonImages 文件夹总是显示。 我还在每种方法和两种方法中都尝试过RestoreDirectory 的变体,但在这两种方法中都没有,但这也不起作用。

提前致谢。


当我将openFileDialog1.InitialDirectory 发送到控制台时,我得到这个输出:

C:\path\to\my\program\here\bin\Debug\..\..\pigeonImages\

我一直认为输入..\ 会提升文件夹级别。 我习惯在 Mac 上写代码,Windows 是否有不同的上文件夹方式?

【问题讨论】:

  • 您是否尝试将 .InitialDirectory 设置为两个文件夹的完整路径,而不是相对路径。
  • @WhoIsRich 我会,但我打算在多台计算机上使用这个程序。文件夹将始终与该程序一起,但不一定在每台计算机硬盘上的同一位置
  • 然后使用 var folder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);获取程序正在运行的位置并附加到它。
  • ShowDialog 之前放置一个断点并添加一个监视表达式Directory.Exists(@"..\..\pigeonImages")。并检查对话框是否设置了初始路径...

标签: c# openfiledialog savefiledialog


【解决方案1】:

我相信您的问题是由于 ....\

请改为执行以下操作。

创建一个 var,这样您只需调用应用程序当前位置一次

//needed namespaces
using System.Reflections
using System.IO;

private string appDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

现在在您的按钮中

openFileDialog1.InitialDirectory = Path.Combine(appDir, "dir1", "dir2");

【讨论】:

  • 只是为了确保,我的按钮应该是:openFileDialog1.InitialDirectory = Path.Combine(appDir, @"..\..\pigeonImages\");
  • 您不想在代码中使用 ..\.. appDir 会为您获取应用程序的位置,然后将目录名称用于您的图像。
  • 你是个传奇。这两个按钮现在打开单独的文件夹,以及它们应该打开的文件夹。还 +1 包括 System.Reflection 我以前无法获得 @WhoIsRich 的工作路径。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-30
  • 2021-05-05
相关资源
最近更新 更多