0

. net winform

Now I get all the fileName under the specified directory. the result is "0001_00001523_028155.sql"

but my goal is only to get "00001523"

how can I do that?

private void loadscriptfolder()
    {
        string folderName = this.textBoxScriptLocation.Text.Trim();
        DirectoryInfo dir = new DirectoryInfo(folderName);
        if (dir.Exists)
        {
            FileSystemInfo[] fs = dir.GetFileSystemInfos();
            foreach (FileSystemInfo fs2 in fs)
            {
                FileInfo file = fs2 as FileInfo;
                if (file != null)
                {
                    listBoxResult.Items.Add(file);
                }                    
            }                
        }
    }

Thank you everyone!!!

2 Answers2

0

Try

    string str = @"0001_00001523_028155.sql";
    var result = str.Split('_')[1];
Mzf
  • 5,210
  • 2
  • 24
  • 37
0

If you just really need to get that part of the file name, then you can just do a string manipulation on its file name.

                FileInfo file = fs2 as FileInfo;
                if (file != null)
                {
                    listBoxResult.Items.Add(file.Name.Split('_')[1]);
                }
aiapatag
  • 3,355
  • 20
  • 24
  • the value of file.Name.Split('_')[1] is right, but I got "Index was outside the bounds of the array." after I run it. – CrystalPeach Jun 07 '13 at 08:46
  • it would be better if you post the stack trace. It could be that your files don't follow a naming convention (eg. [digit]_[digit]_[digit].[extension name]), say `"12345.sql"`. Which in turn fails the `file.Name.Split('_')` because when you split that filename by `_`, the array size is just 1. So having `[1]` will fail because you are accessing the **second** element in that split filename. – aiapatag Jun 07 '13 at 08:50
  • I may know the reason. – CrystalPeach Jun 07 '13 at 08:52
  • glad i was able to help. Welcome to Stackoverflow! btw, when asking for questions, you can see [Ask]. – aiapatag Jun 07 '13 at 08:56