简体   繁体   English

在Console Application中浏览文件夹

[英]browse for folder in Console Application

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;
            }

First you need to add reference to System.Windows.Forms 首先,您需要添加对System.Windows.Forms引用

Then, Add STAThread Attribute to the main method. 然后,将STAThread属性添加到main方法。 This indicates that your program is single-threaded and enabled it to work with COM components (which the System dialogs use). 这表明您的程序是单线程的,并使其能够与COM组件一起使用(系统对话框使用)。

After that only you can use the FolderBrowserDialog with 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
            }
        }


    }
}

User the FolderBrowserDialog 用户FolderBrowserDialog

FolderBrowserDialog b = new FolderBrowserDialog();

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

虽然,为图像UI操作,你可以使用DotImaging.UI

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM