如何使用组合框作为目录路径

How to use a combo box as a directory path

我有 4 个链接到服务器文件夹的组合框,显示文件夹中所有可用的 .dotx。

string[] 文件 = Directory.GetFiles(@"location of the folder", "*.dotx");

        foreach (string file in files)
            comboBox1.Items.Add(Path.GetFileName(file));
        foreach (string file in files)
            comboBox2.Items.Add(Path.GetFileName(file));
        foreach (string file in files)
            comboBox3.Items.Add(Path.GetFileName(file));
        foreach (string file in files)
            comboBox4.Items.Add(Path.GetFileName(file));

我正在使用此视频“https://www.youtube.com/watch?v=0me-ntfD8Rk”中的代码,但稍作改动。

我是 C# 和一般编程的新手,我只是想了解如何使我的按钮中的目录路径(参见 16:13 处的视频)成为由每个示例组合框 1 中的用户。

任何指导将不胜感激。

我想你问的是如何在组合框中引用所选项目?如果是这样,你可以简单地这样做:

comboBox1.Text

因此在 16:13 的视频中,对该方法的调用如下所示:

CreateWordDocument($"path\of\directory\{comboBox1.Text}", @"path\to\output")

其中 $"{variableName}" 是 shorthand 的一部分,可让您在字符串中引用变量。

附带说明一下,您不需要像那样调用同一个循环四次。相反,它看起来像:

foreach(string file in files)
{
    string path = Path.GetFileName(file); // Note I can call GetFileName once and reuse the result
    comboBox1.Items.Add(path);
    comboBox2.Items.Add(path);
    comboBox3.Items.Add(path);
    comboBox4.Items.Add(path);
}