C# 浏览控制台应用程序中的文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15270387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:12:16  来源:igfitidea点击:

browse for folder in Console Application

c#file-upload

提问by user2108195

I currently have to code to allow me to read all of the files of a folder and write them to the console. Below, I also have got the code to select individual files from a directory using a browser. I would like to know how I would be able to select a folder using a browse button.

我目前必须编写代码以允许我读取文件夹的所有文件并将它们写入控制台。下面,我还获得了使用浏览器从目录中选择单个文件的代码。我想知道如何使用浏览按钮选择文件夹。

code to check all files

检查所有文件的代码

  foreach(var path in Directory.GetFiles(@"C:\Name\Folder\"))
    {
       Console.WriteLine(path); // full path
       Console.WriteLine(System.IO.Path.GetFileName(path)); // file name
    }

Code to open dialog box

打开对话框的代码

OpenFileDialog fileSelectPopUp = new OpenFileDialog();
            fileSelectPopUp.Title = "";
            fileSelectPopUp.InitialDirectory = @"c:\";
            fileSelectPopUp.Filter = "All EXCEL FILES (*.xlsx*)|*.xlsx*|All files (*.*)|*.*";
            fileSelectPopUp.FilterIndex = 2;
            fileSelectPopUp.RestoreDirectory = true;
            if (fileSelectPopUp.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = fileSelectPopUp.FileName;
            }

采纳答案by Parimal Raj

First you need to add reference to System.Windows.Forms

首先,您需要添加对 System.Windows.Forms

Then, Add STAThreadAttribute to the main method. This indicates that your program is single-threaded and enabled it to work with COM components (which the System dialogs use).

然后,将STAThreadAttribute添加到 main 方法。这表明您的程序是单线程的,并使其能够与 COM 组件(系统对话框使用的)一起工作。

After that only you can use the FolderBrowserDialogwith the Console Application

之后,只有您可以FolderBrowserDialog与控制台应用程序一起使用

static class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        FolderBrowserDialog fbd = new FolderBrowserDialog();
        if (fbd.ShowDialog() == DialogResult.OK)
        {
            foreach (var path in Directory.GetFiles(fbd.SelectedPath))
            {
                Console.WriteLine(path); // full path
                Console.WriteLine(System.IO.Path.GetFileName(path)); // file name
            }
        }


    }
}

回答by scartag

User the FolderBrowserDialog

用户 FolderBrowserDialog

FolderBrowserDialog b = new FolderBrowserDialog();

if(b.ShowDialog() == DialogResult.OK)
{
  var folderName = b.SelectedPath;
}

回答by dajuric

Alhough, made for image UI operations you can use DotImaging.UI:

不过,对于图像 UI 操作,您可以使用DotImaging.UI

string fileName = UI.OpenFile(); //open-file dialog