2016-02-25 85 views
0

我想要求用戶使用方法指定文件夾路徑並將其保存在數組中,然後允許稍後使用該數組。我遇到的問題是定義返回類型。我應該如何構建該方法?c#內部字符串數組方法

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.我只是開始學習使用方法。

+0

什麼是你需要的返回類型點很重要?只是在這裏替換==> 內部[ - > void < - ] selectFolderTxt( –

回答

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

用法:

string[] files = selectFolderTxt(); 
if (files != null) 
{ 
    // use files 
} 
else 
{ 
    // the user cancelled dialog 
} 
+0

謝謝你一百萬這個幫助太大了,我會在未來重新考慮事情,這使得更多的多功能性 –

+0

它是解決方案但是這種方法並沒有單一的退出點,你可以看看http://stackoverflow.com/questions/4838828/why-should-a-function-have-only-one-exit-point –

0

你應該使用布爾(內部布爾selectFolderTxt(出字符串[]文件))。如果OK,則爲真;如果錯誤或用戶取消了其他假,則爲false。

1

我改變了一點點的解決方案。

單存在

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

不要忘記半-結腸。 –