none
how to read names of files in a folder? RRS feed

  • Question

  • hi,

    please tel me how to get names of files from a folder which i have opened using folder dialog

    and show it in a text box

    thanx

    Wednesday, July 7, 2010 5:57 AM

Answers

  • Hi,

    It is best sample to retrieve the file names from the folder. They implemented here file dialog.

    http://beta.codeproject.com/KB/windows/OpenFileDialog_WM6_S.aspx

    Regards,
    Malleswar

    Wednesday, July 7, 2010 6:17 AM
  • I would use the following:

    string ListFiles(string directory)
    {
      string delimiter = ", ";
      StringBuilder sb = new StringBuilder();
      foreach (FileInfo file in new DirectoryInfo(directory))
      {
        sb.AppendFormat("{0}{1}", delimiter, Path.GetFileName(file.FullName));
      }
      if (sb.Length > delimiter.Length)
      {
        return sb.ToString().Substring(delimiter.Length);
      }
      return string.Empty;
    }

    And then you could fill in the text of your listbox with:

    textbox1.Text = ListFiles(path); // path is the full path to the directory

     

    Just make sure that path is a valid path to a directory.

    Wednesday, July 7, 2010 3:48 PM

All replies

  • Hi,

    It is best sample to retrieve the file names from the folder. They implemented here file dialog.

    http://beta.codeproject.com/KB/windows/OpenFileDialog_WM6_S.aspx

    Regards,
    Malleswar

    Wednesday, July 7, 2010 6:17 AM
  • thanx 4 the answer
    ! but it would be very helpfull if i get C# code for the same.
    Wednesday, July 7, 2010 6:33 AM
  • I would use the following:

    string ListFiles(string directory)
    {
      string delimiter = ", ";
      StringBuilder sb = new StringBuilder();
      foreach (FileInfo file in new DirectoryInfo(directory))
      {
        sb.AppendFormat("{0}{1}", delimiter, Path.GetFileName(file.FullName));
      }
      if (sb.Length > delimiter.Length)
      {
        return sb.ToString().Substring(delimiter.Length);
      }
      return string.Empty;
    }

    And then you could fill in the text of your listbox with:

    textbox1.Text = ListFiles(path); // path is the full path to the directory

     

    Just make sure that path is a valid path to a directory.

    Wednesday, July 7, 2010 3:48 PM