25

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;
            }
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110
user2108195
  • 421
  • 1
  • 4
  • 10
  • Don't know if this will help, but you could try http://stackoverflow.com/questions/31059/how-do-you-configure-an-openfiledialog-to-select-folders – Stanley_A Mar 07 '13 at 11:49
  • This was already answered http://stackoverflow.com/questions/11767/browse-for-a-directory-in-c-sharp... Use a [FolderBrowserDialog](http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx) – clemchen Mar 07 '13 at 11:51

3 Answers3

46

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

Then, Add STAThread Attribute 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).

After that only you can use the FolderBrowserDialog with the Console Application

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


    }
}
Jeff
  • 2,835
  • 3
  • 41
  • 69
Parimal Raj
  • 20,189
  • 9
  • 73
  • 110
3

User the FolderBrowserDialog

FolderBrowserDialog b = new FolderBrowserDialog();

if(b.ShowDialog() == DialogResult.OK)
{
  var folderName = b.SelectedPath;
}
scartag
  • 17,548
  • 3
  • 48
  • 52
1

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

string fileName = UI.OpenFile(); //open-file dialog
dajuric
  • 2,373
  • 2
  • 20
  • 43
  • For this to work, you need to mark your main function (or perhaps your calling function) as [STAThreadAttribute] – Techrocket9 Apr 05 '17 at 19:04