0

I want to ask a user to specify a folder path using a method and save this in the array, then allow that array to be used later on. The problem I have is defining a return type. How should I structure the method?

internal void selectFolderTxt(out string [] files)
{
    FolderBrowserDialog fbd = new FolderBrowserDialog();
    fbd.RootFolder = Environment.SpecialFolder.MyComputer;//This causes the folder to begin at the root folder or your documents
    if (fbd.ShowDialog() == DialogResult.OK)
    {
       string[] files = Directory.GetFiles(fbd.SelectedPath, "*.txt", SearchOption.AllDirectories);//change this to specify file type
    }
    else
    {
        // prevents crash
    }
}

P.S. I Only just started learning to use methods.

Chong Ching
  • 425
  • 3
  • 7

3 Answers3

1

I change the solution little bit.

Single Exist Point important

Why should a function have only one exit-point?

internal string[] selectFolderTxt() {
    string[] resultFiles = null;

    FolderBrowserDialog fbd = new FolderBrowserDialog();
    fbd.RootFolder = Environment.SpecialFolder.MyComputer;//This causes the folder to begin at the root folder or your documents
    if (fbd.ShowDialog() == DialogResult.OK)
    {
       resultFiles = Directory.GetFiles(fbd.SelectedPath, "*.txt", SearchOption.AllDirectories);//change this to specify file type
    }

    return resultFiles 
}
Community
  • 1
  • 1
Sercan Timoçin
  • 658
  • 5
  • 11
0
internal string[] selectFolderTxt() {

    FolderBrowserDialog fbd = new FolderBrowserDialog();
    fbd.RootFolder = Environment.SpecialFolder.MyComputer;//This causes the folder to begin at the root folder or your documents
    if (fbd.ShowDialog() == DialogResult.OK)
    {
       return Directory.GetFiles(fbd.SelectedPath, "*.txt", SearchOption.AllDirectories);//change this to specify file type
    }
    else
    {
    // prevents crash
       return null;
    }
}

Usage:

string[] files = selectFolderTxt();
if (files != null)
{
   // use files
}
else
{
   // the user cancelled dialog
}
  • Thank you times a million this helped so much. I will re-think things in future. This allows for much more versatility. – Chong Ching Feb 25 '16 at 08:20
  • It is solution but This method doesnt have Single Exit Point . You can take a look http://stackoverflow.com/questions/4838828/why-should-a-function-have-only-one-exit-point – Sercan Timoçin Feb 25 '16 at 08:32
0

You should use boolean (internal boolean selectFolderTxt(out string [] files) ). True if OK, false if error or if the user canceled otherwise false.

Leonid Malyshev
  • 475
  • 1
  • 6
  • 14