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.

1
  • What is the return type you need? just replace here ==> internal [-->void<--] selectFolderTxt( Commented Feb 25, 2016 at 8:15

3 Answers 3

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 
}
Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget the semi-colon.
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
}

2 Comments

Thank you times a million this helped so much. I will re-think things in future. This allows for much more versatility.
It is solution but This method doesnt have Single Exit Point . You can take a look stackoverflow.com/questions/4838828/…
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.