C# iterate resources subdirectories - c#

I'm adding some embedded resources to a project, each in their own sub directory, but I'm going to have to add about 50 sub directories, or so.
What I'd like to do is to have the program iterate through each of the sub directories, and then do stuff with the files contained within them, using the directory name as a part of the process. I'm trying to avoid having to write 50 of;
foreach (var resourceFile in Assembly.GetExecutingAssembly().GetManifestResourceNames().Where(x => x.Contains("SubDirectoryName")))
I can't seem to find a way of looping through the directories, without resorting to substring manipulation, is there a built in way to do this?

Based on your description, you want to create sub directory according to the resources and put the resources to the sub directory.
You can refer to the following code example.
string[] files = Directory.GetFiles("D:\\sample");
foreach (var item in files)
{
string filename = Path.GetFileNameWithoutExtension(item);
string name = Path.GetFileName(item);
string path = "D:\\new";
string newpath = Path.Combine(path, filename);
Directory.CreateDirectory(newpath);
File.Copy(item, Path.Combine(newpath, name));
Console.WriteLine(filename);
}
Console.ReadKey();
Note: All the resource files come from D:\sample and the code will create the sub
directory in the path of D:\new. Finally, the code will copy these source files to the
sub directory.
Hope it can help you.

Related

Is there an algorithms that can list all file in the folder (for C#)?

Hello StackOverflow community,
I'm working for a C# web application that can show all necessary files in one folder. For example, you have a folder named "Maps" that stores all information about New York City. I will describe this folder here: The bolded word is folders.
Folder Maps:
->NewYorkCity
->>satellite.png
->>coordinates.txt
->>bridges.png
->>Road1
->>>satellite1.png
->>>roads.txt
->>>houses.png
As you can see, inside folder Maps we have folder NewYorkCity, and inside of this, we have folder Road1. Now I want to collect all files that have "*.png" type. It means I want to collect all images inside the root folder. The problem here is the algorithm to collect the file. I have thought to use "for loops" but I don't know the number of subfolders so I assumed it was impossible.
Here is the code to list the file with specified type that I have used but it works for files that in one folder and doesn't have any subfolders.
DirectoryInfo dInfo = new DirectoryInfo(zipPath); //Assuming Test is your Folder
FileInfo[] Files = dInfo.GetFiles("*.png"); //Getting Text files
string str = "";
foreach (FileInfo file in Files)
{
str = str + ", " + file.Name;
}
I hope you understand my question. Thank you.
You could start by reading the documentation, where you would find System.IO.DirectoryInfo.
Create a DirectoryInfo instance, and use, depending on what you want/need, any of its methods
EnumerateDirectories()
EnumerateFiles()
EnumerateFileSystemInfos()
Like so:
DirectoryInfo di = new DirectoryInfo(#"c:\Maps");
foreach (var fsi in di.EnumerateFileSystemInfos("*", SearchOptions.AllDirectories)
{
// Do something useful with fsi here
}

Delete all folders in parent folder except where sub folder contains specific file

I'm having problems keeping 1 folder which contains an image I want to keep.
I'm currently using the code below:
DirectoryInfo di = new DirectoryInfo(pathToMedia);
foreach (var image in di.GetFiles())
{
if (!image.Name.Contains(emailImage))
{
di.Delete(true);
}
}
The above does not work as I cannot seem to get the file name of the image inside the sub-folder, any help would be appreciated
The code is not able to find the file as GetFiles(string) method only returns the file in the current directory and not in the sub-folders (an overload exists which allows to get all files, but that wont be useful here as we need the directory information as well). If you want to check for the files in all sub-folders then you will have to recursively do through the entire structure.
The code below shows how to do it, in your case instead of writing to console you will just check if it matches to the file you are searching.
You can see the detail about these methods in api documentation
As mentioned in the documentation it might be beneficial for you to use EnumerateFiles in case your folders are going to have a large number of files.
// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
public static 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 static void ProcessFile(string path)
{
Console.WriteLine("Processed file '{0}'.", path);
}

Loop Through Each Sub Directories In Sub Directories

I have a main folder which contains many sub directories. Inside each sub directory, there are many sub directories.
Does anyone knows how can I loop through the many sub directories in each sub directory?
This is my codes currently:
if (Directory.Exists(MainDirectory))
{
foreach (DirectoryInfo SubDir in new DirectoryInfo(MainDirectory).GetDirectories())
{
foreach (FileInfo Image in SubDir.GetFiles())
{
Image.Delete();
}
SubDir.Delete(true);
}
Directory.Delete(MainDirectory, true);
}
My current codes will only loop through the images from each subdirectory from the main directory.
Please help me on this.
You can use the Directory SearchOption.AllDirectories or you can use recursive call for it, whichever is appropriate.
If what you really interested in are files rather than to enter the sub-directories themselves, the method that you can use is Directory.GetFiles, something like this:
string[] files = Directory.GetFiles(folderpath, "*", SearchOption.AllDirectories); //"*" denotes all file format
the return is string[] which contains all filepaths in the given folderpath including those which are in the sub-directories.
You can change the SearchPattern ("*" in the example) to suit the file search pattern (formats) which you need.
If you really need to enter the sub-directory however, you can create recursive calls and in the call, you can check if the directory has further (deeper) folder by using DirectoryInfo.GetDirectories()

Ways to get the relative path of a folder

I have one folder named "Images" in my project. I want to get the path of the Image folder so that I can browse that and get the files.
I'm using below piece of code for my above requirement and it is working fine.
string basePath = AppDomain.CurrentDomain.BaseDirectory;
basePath = basePath.Replace("bin", "#");
string[] str = basePath.Split('#');
basePath = str[0];
string path = string.Format(#"{0}{1}", basePath, "Images");
string[] fileEntries = Directory.GetFiles(path);
foreach (string fileName in fileEntries)
listBox.Items.Add(fileName);
Just want to know like is there any elegant way of doing this? What are the best ways of getting the folder path?
This is what i usually use:
string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Note that this returns the directory of the assembly that contains the currently executing code (i assume this is your main executable).
To get the parent directory of the resulting path, you can also use
Path.GetDirectoryName(appDirectory);
I would advice against depending on the Visual Studio project structure in your code, though. Consider adding the images folder as content to your application, so that it resides in a subdirectory in the same directory as your executable.
If you are just trying to reference a directory with a fixed relationship to another, then you can just use the same .. syntax you'd use at the command line?
You should also use the methods in the Path class (eg Path.Combine) rather than all that string manipulation.

Is there a way to find a file by just its name in C#?

We use absolut path or relatvie path to find a file in our C# application right now. Is there a way to find the file just by its name if the file is under the currect working directory or under one of the "paths"?
Use absolute pathe is not good and use relative path is not good enough because we may change project structure by rename or move project folders. If we our code can automatically search current working directory, its subfolders and search system path, that will be more flexible.
thanks,
You can easily build a recursive function to do this for you. Look at Directory.GetDirectories and Directory.GetFiles, both under System.IO
Try this:
string target = "yourFilenameToMatch";
string current = Directory.GetCurrentDirectory();
// 1. check subtree from current directory
matches=Directory.GetFiles(current, target, SearchOption.AllDirectories);
if (matches.Length>0)
return matches[0];
// 2. check system path
string systemPath = Environment.GetEnvironmentVariable("PATH");
char[] split = new char[] {";"};
foreach (string nextDir in systemPath.Split(split))
{
if (File.Exists(nextDir + '\\' + target)
{
return nextDir;
}
}
return String.Empty;
You could call Directory.GetFiles for each root folder in which you want to search for the file. the parameter searchOption allow you to specify whether the search operation look in all subdirectories or only the directory specified. E.g:
public string GetFileName(string[] folders,string fileName) {
string[] filePaths;
foreach(var folder in folders) {
filePaths=Directory.GetFiles(folder,fileName,SearchOption.AllDirectories)
if (filePaths.Lenght>0)
return filePaths[0];
}
}
Try this:
Directory.EnumerateFiles(pathInWhichToSearch, fileNameToFind, SearchOption.AllDirectories);
And, you need to use:
using System.IO;
on top of your class.
This searches all subdirectories of pathInWhichToSearch for a file with name fileNameToFind (it can be a pattern too - like *.txt) and returns result as IEnumerable<string> with full paths of found files.
You can get the exe's directory using
Path.GetDirectoryName(Application.ExecutablePath);
Example Code: http://www.csharp-examples.net/get-application-directory/
And then, you can search the folders from there using recursion. This is a good article on recursive searching for files:
http://support.microsoft.com/kb/303974

Categories

Resources