Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for Sub directory in C#

I am storing the files extracted from a rar/zip file in a folder.
After that I am storing the files inside that folder to a database.
The problem is it stores only the files in the folder not the sub directories and its files.

How to find if the folder has any sub directories.
I am using the code below

 Directory.CreateDirectory(StorageRoot + path + New_folder);
 decom(StorageRoot + path + New_folder, StorageRoot + path + file.FileName);
 foreach (var access_file in Directory.GetFiles(StorageRoot + path + New_folder))
 {                     
     string new_name=System.IO.Path.GetFileName(access_file);
     FileInfo f = new FileInfo(StorageRoot + path + New_folder+ "/" + new_name);
     int new_size = unchecked((int)f.Length);
     string new_path = path + New_folder;
     statuses.Add(new FilesStatus(new_name, new_size, new_path, StorageRoot, data));
 }

How to get the list of files and directories in a folder. and save them in db?

like image 533
Jhonny Avatar asked Apr 06 '13 11:04

Jhonny


3 Answers

To get the files and directories in a folder you can use Directory.GetFiles() and Directory.GetDirectories()

Use recursion or Queue to recursively traverse directories.

Example with recursion:

void Traverse(string directory)
{
    foreach(var dir in Directories.GetDirectories(directory))
    {
         Traverse(directory);
    }

    // Your code here
}
like image 108
Nikolay Kostov Avatar answered Sep 28 '22 04:09

Nikolay Kostov


This may helps:

    System.IO.DirectoryInfo info = new System.IO.DirectoryInfo("YOUR PATH");

    //List of directories
    var result = info.GetDirectories().Select(i => i.FullName);

You can use GetDirectories to get sub folder DirectoryInfo's and iterate through them untill Getdirectories returns nothing.

like image 43
Hossein Narimani Rad Avatar answered Sep 28 '22 04:09

Hossein Narimani Rad


You can use Directory.GetFileSystemEntries() to get a list of both files and directories. http://msdn.microsoft.com/en-us/library/system.io.directory.getfilesystementries.aspx

like image 24
Drew R Avatar answered Sep 28 '22 03:09

Drew R