简体   繁体   中英

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?

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
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM