Monday 16 April 2012

Beginning .Net : Get list of files from directory programmatically using .Net

Sometimes we want list of files and its details like file name , size , last access time etc... of a directory programmatically.
We can achieve this using DirectoryInfo and FileInfo Class. These classes are available in available in System.IO Namespace.
There is one method GetFiles() of DirectoryInfo class to get array of FileInfo class of particular directory.
This GetFiles() method accepts various parameters like , Search Pattern and Search Option.
Search Pattern means to get file list particular of give search pattern like you can pass "*.txt" it will get only ".txt" files.
Or like "System*" , it will get file name whose name start with System.

Here are sample example to list out all file and it's details of particular directory
 System.Text.StringBuilder objSB = new System.Text.StringBuilder();
        System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo("d:\\");
        objSB.Append("<table>");
        objSB.Append("<tr><td>FileName</td><td>Last Access</td><td>Last Write</td> <td>Attributes                  </td><td>Length(Byte)</td><td>Extension</td></tr>");
        foreach (System.IO.FileInfo objFile in directory.GetFiles("*.*"))
        {
            objSB.Append("<tr>");

            objSB.Append("<td>");
            objSB.Append(objFile.Name);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objFile.LastAccessTime);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objFile.LastWriteTime);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objFile.Attributes);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objFile.Length);
            objSB.Append("</td>");

            objSB.Append("<td>");
            objSB.Append(objFile.Extension);
            objSB.Append("</td>");
           
            objSB.Append("</tr>");
        }
        objSB.Append("</table>");

        Response.Write(objSB.ToString());

This example display list of file in html table structure.

Here is another post for  "Get list of all files of directory or folder using LINQ using .Net Framework 4 with C# Examples and VB.Net Examples " , In this post we are using .Net Framework 4 features. Click Here to view this post. Click here...


No comments:

Post a Comment