Home Asp.net Get Folder Files List and Export to CSV in .NET

Get Folder Files List and Export to CSV in .NET

25
0

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.

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

[wpdm_file id=38]

LEAVE A REPLY

Please enter your comment!
Please enter your name here
Captcha verification failed!
CAPTCHA user score failed. Please contact us!