2016-02-25 49 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

不要忘记半-结肠。 –