AspnetO

We code, that works!

  • Home
  • Asp.net
  • MVC
  • Interview Questions
You are here: Home / Asp.net / Get Folder Files List and Export to CSV in .NET

Get Folder Files List and Export to CSV in .NET

By: Mayank Modi | Falls In: Asp.net, C#, VB | Last Updated: Oct 07, 2020

In my previous tutorials, I’d explained how to upload and download files in asp.net, get directory files list with it’s sub-directory and other more cracking tutorials on Files, JavaScript, jQuery in Asp.net with an example code.

Now here in this tutorial, I’ll explain how to get folder files list and export to csv or excel spread sheet in asp.net using c# as well as vb.net.

To get list of file names from the specified directory or folder, we need to use static method Directory.Get ­Files included in System.IO namespace. This method returns the names of files (including their full path) from the specified directory structure. I’ve already explained list of available folder scanning options to get files including it’s sub-folders, file name with extension here.

Follow two easy steps to achieve this functionality with ease:

Step 1: Copy CsvExport.cs or CsvExport.vb file depends on your programming language. It’s a abstract class needed to export files list into csv or excel sheet.

Note: To get file, you need to download example code from below. Make sure you change the namespace regarding to your project to integrate in your working project.

Step 2: Copy and paste following code to your project wherever you want to implement this functionality. Just make sure to replace your directory paths and include required namespaces within your project.

Get Folder Files List and Export to CSV or Excel in C#

Following is the complete example that I demonstrate to get folder files list and export to csv or excel spread sheet recursively in .net using c#:

public static void StartProcees()
{
// replace your base path where to get files list
string baseDirectory = @”C:\MyFolder\”;// get list of files from the specific directory
string[] allFiles = Directory.GetFiles(baseDirectory, “*.*”, SearchOption.AllDirectories)
.OrderByDescending(x => x.Split(‘\\’).Length).ToArray();

if (allFiles.Count() > 0)
{
// replace your target path where to export files list
string baseExportDirectory = @”C:\MyExportFolder\”;
string baseExportPath = baseExportDirectory + “FilesList.csv”;

PreparingFilesList(allFiles, baseDirectory, baseExportDirectory, baseExportPath);
}
}

private static void PreparingFilesList(string[] allFiles, string baseDirectory,
string baseExportDirectory, string baseExportPath)
{
var csvExport = new CsvExport();
try
{
int fileCounter = 0;
foreach (string file in allFiles)
{
fileCounter++;
csvExport.AddRow();

string fileName = Path.GetFileName(file);
string dirPath = GetNeededDirectoriesFromPath(baseDirectory, file);

int dirCounter = 0;
var deepDirectories = dirPath.Split(‘\\’);
foreach (string dir in deepDirectories)
{
dirCounter++;
if (dir.IndexOf(fileName) == -1)
{
csvExport[“Dir “ + dirCounter] = dir;
}
}
csvExport[“File Name”] = fileName;
}

// create export directory if not exists
if (!Directory.Exists(baseExportDirectory))
Directory.CreateDirectory(baseExportDirectory);

// delete old files if already exists
if (File.Exists(baseExportPath))
File.Delete(baseExportPath);

// start exporting files to export directory
csvExport.ExportToFile(baseExportPath);
}
catch (UnauthorizedAccessException UAEx)
{
Console.WriteLine(UAEx.Message);
}
catch (PathTooLongException PathEx)
{
Console.WriteLine(PathEx.Message);
}
}

private static string GetNeededDirectoriesFromPath(string basePath, string path)
{
// normalize paths
basePath = Path.GetFullPath(basePath);
path = Path.GetFullPath(path);

// same path case
if (basePath == path)
return string.Empty;

// path is not contained in basePath case
if (!path.StartsWith(basePath))
return string.Empty;

// extract relative path
if (basePath[basePath.Length – 1] != Path.DirectorySeparatorChar)
{
basePath += Path.DirectorySeparatorChar;
}

return path.Substring(basePath.Length);
}

Get Folder Files List and Export to CSV or Excel in Vb.net

Following is the complete example that I demonstrate to get folder files list and export to csv or excel spread sheet recursively in .net using vb.net:

Public Shared Sub StartProcees()
‘ replace your base path where to get files list
Dim baseDirectory As String = “C:\MyFolder\”‘ get list of files from the specific directory
Dim allFiles() As String = Directory.GetFiles(baseDirectory, “*.*”, SearchOption.AllDirectories)
.OrderByDescending(Function(x) x.Split(“\”c).Length).ToArray()

If allFiles.Count() > 0 Then
‘ replace your target path where to export files list
Dim baseExportDirectory As String = “C:\MyExportFolder\”
Dim baseExportPath As String = baseExportDirectory & “FilesList.csv”

PreparingFilesList(allFiles, baseDirectory, baseExportDirectory, baseExportPath)
End If
End Sub

Private Shared Sub PreparingFilesList(ByVal allFiles() As String, ByVal baseDirectory As String,
ByVal baseExportDirectory As String, ByVal baseExportPath As String)
Dim csvExport = New CsvExport()
Try
Dim fileCounter As Integer = 0
For Each file As String In allFiles
fileCounter += 1
csvExport.AddRow()

Dim fileName As String = Path.GetFileName(file)
Dim dirPath As String = GetNeededDirectoriesFromPath(baseDirectory, file)

Dim dirCounter As Integer = 0
Dim deepDirectories = dirPath.Split(“\”c)
For Each dir As String In deepDirectories
dirCounter += 1
If dir.IndexOf(fileName) = -1 Then
csvExport(“Dir “ & dirCounter) = dir
End If
Next dir
csvExport(“File Name”) = fileName
Next file

‘ create export directory if not exists
If Not Directory.Exists(baseExportDirectory) Then
Directory.CreateDirectory(baseExportDirectory)
End If

‘ delete old files if already exists
If File.Exists(baseExportPath) Then
File.Delete(baseExportPath)
End If

‘ start exporting files to export directory
csvExport.ExportToFile(baseExportPath)
Catch UAEx As UnauthorizedAccessException
Console.WriteLine(UAEx.Message)
Catch PathEx As PathTooLongException
Console.WriteLine(PathEx.Message)
End Try
End Sub

Private Shared Function GetNeededDirectoriesFromPath(ByVal basePath As String,
ByVal path As String) As String
‘ normalize paths
basePath = System.IO.Path.GetFullPath(basePath)
path = System.IO.Path.GetFullPath(path)

‘ same path case
If basePath = path Then
Return String.Empty
End If

‘ path is not contained in basePath case
If Not path.StartsWith(basePath) Then
Return String.Empty
End If

‘ extract relative path
If basePath.Chars(basePath.Length – 1) <> System.IO.Path.DirectorySeparatorChar Then
basePath &= System.IO.Path.DirectorySeparatorChar
End If

Return path.Substring(basePath.Length)
End Function

Example Usage

You can use above example by simply calling the StartProcees() method wherever you want to use.

You may also like, 100+ Frequently Asked Interview Questions on Asp.net, Top 10 OOPS Concepts in .NET C# with Examples here.

That’s it, now you’ll be able to get folder files list and export to csv or excel to specified folder path without any trouble.

Example Result

Get Folder Files List and Export to CSV in .NET

Download Example

Icon

Get Folder Files List and Export to CSV in .NET

1 file(s) 54.44 KB
Download This Example

Signup Today And Get Latest Tutorials For Free!

Subscribe to us and get free latest tutorials notifications whenever we publish a new contents.

<

About Mayank Modi

Mayank is a web developer and designer who specializes in back-end as well as front-end development. He's a Founder & Chief Editor of AspnetO. If you'd like to connect with him, follow him on Twitter as @immayankmodi.

Leave a Reply Cancel reply

Search Your Topic



Social Connections

  • 1,438 Fans
  • 3,087 Followers
  • 50 Followers
  • 1,559 Subscribers

Get Latest Tutorials For Free



Top Posts

  • Pass Multiple Parameters in Asp.net QueryString Example
  • CSS3 Transition: fadeIn and fadeOut like Effects to Hide Show Elements
  • Show Confirm Message Box from Code-behind in Asp.net
  • Send HTML Webpage Content as Email Body in Asp.net C# Vb.net
  • Asp.net Menu Control Example

Contribute to AspnetO

If you want to contribute your unique blog articles or tutorials (Free / Paid) to AspnetO in any languages, you're most welcome. Just send me your previous articles, and topics on which you are interested to post an tutorial. Contact us at email listed in contact us page. Selected candidates will be contacted.

Search by Tags

Ado.net Ajax appSettings Asp.net C# CheckBox CheckBoxList ConnectionStrings Control CSS CSS3 Difference Download DropDownList Export Facebook fadeIn fadeOut fadeTo fadeToggle File File Extension FileUpload Function GridView IIS Interview Questions JavaScript jQuery MVC OOP RadioButtonList RDP Repeater Send Mail Solutions Split SQL Stored Procedure TextBox Upload Validation VB Web.config Web Hosting

The Man Behind AspnetO

Mayank Modi

Hi there,

Myself Mayank Modi, a Full Stack Developer (.NET Stack) and a blogger from Surat, India.

I'm welcoming you to my blog - AspnetO, a programmers community blog where we code, that works!

I started AspnetO as a hobby and now we're growing day by day. We're now having 5000+ programmers that get benefits and learn new things about website design and development under our community blog.

Here at AspnetO, I write about Beginners to Advance level of tutorials on programming languages like Asp.net using C# and Vb.net, MVC, SQL Server, JavaScript, jQuery etc. In sort, all about .NET Framework and website development stuff and sometimes sharing tips and tricks that can help you to grow up your programming skills.

You can get more details about me and my blog at About us page.

Subscribe To Newsletter

Enter your email address to subscribe to this blog and receive notifications of new posts right to your inbox

Join 1000+ other subscribers

<

Recent Posts

  • Main Difference between SessionState and ViewState in Asp.net
  • How to Get appSettings Value from Web.config File?
  • How to Get ConnectionString from Web.config in Asp.net?
  • Difference between appSettings and connectionStrings in Web.config
  • Get Folder Files List and Export to CSV in .NET
  • Get Files List From Directory Recursively in C# Vb.net
  • Get Hash Value From Current Page URL In jQuery
  • Handle Multiple Submit Buttons in Single MVC Form

Copyright © 2014 - 2021 · All Rights Reserved.

About | Copyrights | Privacy | Terms | Contact | Advertise | Sitemap
Previous Get Files List From Directory Recursively in C# Vb.net
Next Difference between appSettings and connectionStrings in Web.config