All posts tagged directory

Get all files in Directory and Sub directory using Asp.net

Get all files in Directory and Sub directory using Asp.net is easy task we have to use this name space using System.IO;

And Call the GetFiles() function to get all files from the directory we use MapPath(“.”) to get the root folder and show all files in side it. If you want to show a perticular folder’s file then change (“.”) to (“foldername”) then it will show all the files in side the folder.


  public void GetFiles()
 {
      string    path =    MapPath(".");
        if (File.Exists(path))

        {
            // File path
            ProcessFile(path);
        }

 else if (Directory.Exists(path))

{
            // This path is a directory

            ProcessDirectory(path);

        }

    }
  
    // Process all files in the directory passed in, recurse on any directories

    // that are found, and process the files they contain.

    public void ProcessDirectory(string targetDirectory)
{
        // Process the list of files found in the directory.

        string[] fileEntries = Directory.GetFiles(targetDirectory);

        foreach (string fileName in fileEntries)

            ProcessFile(fileName);

         // Recurse into subdirectories of this directory.

        string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);

        foreach (string subdirectory in subdirectoryEntries)

            ProcessDirectory(subdirectory);

    }

    // Insert logic for processing found files here.

    public void ProcessFile(string path)

    {

        FileInfo fi = new FileInfo(path);

        Response.Write("Path: " + path + "<br/>");
     

    }

 

The above GetFiles() method print this

Path: H:\CATEGORY WISE CODE LIBRARY ASP.NET\SEO\ASP\About.aspx
Path: H:\CATEGORY WISE CODE LIBRARY ASP.NET\SEO\ASP\About.aspx.cs
Path: H:\CATEGORY WISE CODE LIBRARY ASP.NET\SEO\ASP\About.aspx.designer.cs
Path: H:\CATEGORY WISE CODE LIBRARY ASP.NET\SEO\Contact.aspx.cs
Path: H:\CATEGORY WISE CODE LIBRARY ASP.NET\SEO\Contact.aspx.designer.cs
Path: H:\CATEGORY WISE CODE LIBRARY ASP.NET\SEO\Default.aspx
Path: H:\CATEGORY WISE CODE LIBRARY ASP.NET\SEO\Default.aspx.cs

 

Multiple Filters On Directory.GetFiles Method

If you tried to use Directory class located in System.IO namespace, you noticed GetFiles method that is used to retrieve names of the files of specified directory. But, unlike good practices in some other programming tools, Directory.GetFiles method can’t return multiple extension (unless you use “*” filter that returns all files but you can get that without using filter at all).

There are few different solutions to select multiple file extensions with GetFiles method. Here is mine, I wrote a function that takes same parameters like GetFiles method but its filter supports multiple file filters:

[ C# ]

/// <summary>
/// Returns file names from given folder that comply to given filters
/// </summary>
/// <param name="SourceFolder">Folder with files to retrieve</param>
/// <param name="Filter">Multiple file filters separated by | character</param>
/// <param name="searchOption">File.IO.SearchOption,
/// could be AllDirectories or TopDirectoryOnly</param>
/// <returns>Array of FileInfo objects that presents collection of file names that
/// meet given filter</returns>
public string[] getFiles(string SourceFolder, string Filter,
 System.IO.SearchOption searchOption)
{
 // ArrayList will hold all file names
ArrayList alFiles = new ArrayList();
 
 // Create an array of filter string
 string[] MultipleFilters = Filter.Split('|');
 
 // for each filter find mathing file names
 foreach (string FileFilter in MultipleFilters)
 {
  // add found file names to array list
  alFiles.AddRange(Directory.GetFiles(SourceFolder, FileFilter, searchOption));
 }
 
 // returns string array of relevant file names
 return (string[])alFiles.ToArray(typeof(string));
}

[smProductImageAdd src="http://learneveryday.net/codecanyon/adverticement/add_codecnayon_smart-social-share-asp.net.png" alt= "Smart Social Share" href="http://codecanyon.net/item/smart-social-share/160097" title="Smart Social Share (Asp.net control)" description="Smart Social share is a asp.net control . Which helps you to give user to share your content with social book mark site." ref="marifdu"]

[ VB.NET ]


''' <summary>
''' Returns file names from given folder that comply to given filters
''' </summary>
''' <param name="SourceFolder">Folder with files to retrieve</param>
''' <param name="Filter">Multiple file filters separated by | character</param>
''' <param name="searchOption">File.IO.SearchOption,
''' could be AllDirectories or TopDirectoryOnly</param>
''' <returns>Array of FileInfo objects that presents collection of file names that
''' meet given filter</returns>
Public Function getFiles(ByVal SourceFolder As String, ByVal Filter As String, _
 ByVal searchOption As System.IO.SearchOption) As String()
 ' ArrayList will hold all file names
 Dim alFiles As ArrayList = New ArrayList()
 
 ' Create an array of filter string
 Dim MultipleFilters() As String = Filter.Split("|")
 
 ' for each filter find mathing file names
 For Each FileFilter As String In MultipleFilters
  ' add found file names to array list
  alFiles.AddRange(Directory.GetFiles(SourceFolder, FileFilter, searchOption))
 Next
 
 ' returns string array of relevant file names
 Return alFiles.ToArray(Type.GetType("System.String"))
End Function

You can copy this function to your application. This example call getFiles function and lists selected file names including sub directories:

[ C# ]

protected void btnListSomeFiles_Click(object sender, EventArgs e)
{
// Request files with gif, jpg, png, bmp, aspx and vb extension
// Extensions are separated with | character
string[] sFiles = getFiles(Server.MapPath("~/"),
 "*.gif|*.jpg|*.png|*.bmp|*.aspx|*.vb",
 SearchOption.AllDirectories);
 
// Write returned file names on page
foreach (string FileName in sFiles)
{
 Response.Write(FileName + "<br />");
}
}

[ VB.NET ]


Protected Sub btnListSomeFiles_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnListSomeFiles.Click
 ' Request files with gif, jpg, png, bmp, aspx and vb extension
 ' Extensions are separated with | character
 Dim sFiles() As String = getFiles(Server.MapPath("~/"), _
  "*.gif|*.jpg|*.png|*.bmp|*.aspx|*.vb", _
  SearchOption.AllDirectories)
 
 ' Write returned file names on page
 For Each FileName As String In sFiles
  Response.Write(FileName + "<br />")
 Next
End Sub

Getting file names with multiple filters is very common task and some newer version of .Net Framework will probably have Directory.getFiles method that supports multiple filters. Until then you can use this function and get quite satisfactory results. Happy coding!

How To Get A List Of Files From Folder In ASP.NET?

If you need to get a list of files from some folder you need to use DirectoryInfo class from System.IO namespace. One sample approach that shows all gif images from Images folder in ListBox control named lstFiles, could be like this:

[ C# ]


// We need this namespace
using System.IO;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // We'll read all files from Images subfolder
        DirectoryInfo diFiles = new DirectoryInfo(Server.MapPath("~/Images/"));
        // Takes all .gif images,
        // You can set some other filter or
        // *.* for all files
        lstFiles.DataSource = diFiles.GetFiles("*.gif");
        // bind data to list box
        lstFiles.DataBind();
    }
}

[ VB.NET ]



' We need this namespace
Imports System.IO
 
 
Partial Class _Default
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ' We'll read all files from Images subfolder
        Dim diFiles As DirectoryInfo = New DirectoryInfo(Server.MapPath("~/Images/"))
        ' Takes all .gif images,
        ' You can set some other filter or
        ' *.* for all files
        lstFiles.DataSource = diFiles.GetFiles("*.gif")
        ' bind data to list box
        lstFiles.DataBind()
    End Sub
End Class

How to loop through all files in a folder using C#

Bellow is the code for loop throught all files in a folder.

// How much deep to scan. (of course you can also pass it to the method)
const int HowDeepToScan=4;

public static void ProcessDir(string sourceDir, int recursionLvl) 
{
  if (recursionLvl<=HowDeepToScan)
  {
    // Process the list of files found in the directory.
    string [] fileEntries = Directory.GetFiles(sourceDir);
    foreach(string fileName in fileEntries)
    {
       // do something with fileName
       Console.WriteLine(fileName);
    }

    // Recurse into subdirectories of this directory.
    string [] subdirEntries = Directory.GetDirectories(sourceDir);
    foreach(string subdir in subdirEntries)
       // Do not iterate through reparse points
       if ((File.GetAttributes(subdir) &
            FileAttributes.ReparsePoint) !=
                FileAttributes.ReparsePoint)

            ProcessDir(subdir,recursionLvl+1);
  }
}

How To Make Directory In ASP.NET?

To create directory on web server with ASP.NET server side code, you can use this code:

[ C# ]

using System;
using System.Data;
using System.Configuration;
// We need this namespace to create directory
using System.IO;
 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string NewDir = Server.MapPath("New Folder");
        // Call function for creating a directory
        MakeDirectoryIfExists(NewDir);
    }
 
    private void MakeDirectoryIfExists(string NewDirectory)
    {
        try
        {
            // Check if directory exists
            if (!Directory.Exists(NewDirectory))
            {
                // Create the directory.
                Directory.CreateDirectory(NewDirectory);
            }
        }
        catch (IOException _ex)
        {
            Response.Write(_ex.Message);
        }
    }
}

[ VB.NET ]


' We need this namespace to make a directory
Imports System.IO
 
Partial Class _Default
    Inherits System.Web.UI.Page
 
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim NewDir As String = Server.MapPath("New Folder")
        ' Call function for creating a directory
        MakeDirectoryIfExists(NewDir)
    End Sub
 
    Private Sub MakeDirectoryIfExists(ByVal NewDirectory As String)
        Try
            ' Check if directory exists
            If Not Directory.Exists(NewDirectory) Then
                ' Create the directory.
                Directory.CreateDirectory(NewDirectory)
            End If
        Catch _ex As IOException
            Response.Write(_ex.Message)
        End Try
    End Sub