Wednesday, August 6, 2014

List Files and Folders in C#.Net





using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ListFilesAndFolders
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            folderBrowser1.ShowDialog(this);
            String str = DirSearch(folderBrowser1.SelectedPath);
            txtFiles .Text = str;
        }

        private String DirSearch(string sDir)
        {
            try
            {
                String strFile = String.Empty;
                String strNo = String .Empty ;
                Int32 nCount = 0;
                this.Cursor = Cursors.WaitCursor;
                foreach (string f in Directory.GetFiles(sDir))
                {
                    if (chkWithNumber.Checked == true) strNo = Convert.ToString(nCount + 1) + ". "; else strNo = "";

                    strFile = strFile + strNo + f + "\r\n";
                    nCount = nCount + 1;
                }

                foreach (string d in Directory.GetDirectories(sDir))
                {
                    foreach (string f in Directory.GetFiles(d))
                    {
                        if (chkWithNumber.Checked == true) strNo = Convert.ToString(nCount + 1) + ". "; else strNo = "";
                        strFile =strFile + strNo + f + "\r\n";
                        nCount = nCount + 1;
                    }
                    DirSearch(d);
                }
               
                lblCount.Text = "File Count :" + Convert.ToString ( nCount);
                this.Cursor = Cursors.Default;

                return strFile;
            }
            catch (System.Exception excpt)
            {
                Console.WriteLine(excpt.Message);
                return "";
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtFiles.Clear();
        }
    }
}

No comments:

Post a Comment