Create directory structure - c#

Is there any way I can create a list with all the folders and files that are in a directory? I will specify the path and I want to list all its child folders and files, and write them in a txt file, or maybe an xml file to make it easier to read.

The Directory.GetFiles method should give you a list of all files, along with their full paths:
string[] filePaths = Directory.GetFiles(#"c:\MyDir\", "*.*", SearchOption.AllDirectories);

Directory.GetFiles and Directory.GetDirectories methods should help

This is a good link to get all files:
http://www.csharp-examples.net/get-files-from-directory/
And to get all directories: use Directories.GetFolders() instead.
Then you have to make a for loop or something to traverse them them.
Perhaps a recursive method would be a good selection. Something like
void PrintFilesAndFolders(string directory)...

Related

"Illegal characters in path" error using wildcards with Directory.GetFiles

I have a directory with multiple sub directories that contain .doc files. Example:
C:\Users\user\Documents\testenviroment\Released\test0.doc
C:\Users\user\Documents\testenviroment\Debug\test1.doc
C:\Users\user\Documents1\testenviroment\Debug\test2.doc
C:\Users\user\Documents1\testenviroment\Released\test20.doc
I want to get all the test*.doc files under all Debug folders. I tried:
string[] files = Directory.GetFiles(#"C:\Users\user", "*Debug\\test*.doc",
SearchOption.AllDirectories);
And it gives me an "Illegal characters in path" error.
If I try:
string[] files = Directory.GetFiles(#"C:\Users\user", "\\Debug\\test*.doc",
SearchOption.AllDirectories);
I get a different error: "Could not find a part of the path C:\Users\user\Debug".
You are including a folder within the search pattern which isn't expected. According to the docs:
searchPattern Type: System.String The search string to match against
the names of files in path. This parameter can contain a combination
of valid literal path and wildcard (* and ?) characters (see Remarks),
but doesn't support regular expressions.
With this in mind, try something like this:
String[] files = Directory.GetFiles(#"C:\Users\user", "test*.doc", SearchOption.AllDirectories)
.Where(file => file.Contains("\\Debug\\"))
.ToArray();
This will get ALL the files in your specified directory and return the ones with Debug in the path. With this in mind, try and keep the search directory narrowed down as much as possible.
Note:
My original answer included EnumerateFiles which would work like this (making sure to pass the search option (thanks #CodeCaster)):
String[] files = Directory.EnumerateFiles(#"C:\Users\user", "test*.doc", SearchOption.AllDirectories)
.Where(file => file.Contains("\\Debug\\"))
.ToArray();
I've just run a test and the second seems to be slower however it might be quicker on a larger folder. Worth keeping in mind.
Edit: Note from #pinkfloydx33
I've actually had that practically take down a system that I had
inherited. It was taking so much time trying to return the array and
killing the memory footprint as well. Problem was diverted converting
over to the enumerable counterparts
So using the second option would be safer for larger directories.
The second parameter, the search pattern, works only for filenames. So you'll need to iterate the directories you want to search, then call Directory.GetFiles(directory, "test*.doc") on each directory.
How to write that code depends on how robust you want it to be and what assumptions you want to make (e.g. "all Debug directories are always two levels into the user's directory" versus "the Debug directory can be at any level into the user's directory").
See How to recursively list all the files in a directory in C#?.
Alternatively, if you want to search all subdirectories and then discard files that don't match your preferences, see Searching for file in directories recursively:
var files = Directory.GetFiles(#"C:\Users\user", "test*.doc", SearchOption.AllDirectories)
.Where(f => f.IndexOf(#"\debug", StringComparison.OrdinalIgnoreCase) >= 0);
But note that this may be bad for performance, as it'll scan irrelevant directories.

Get Files and Folders by Folder and File wildcard

I have a pattern like ..\\*\\your_magic*.txt*zip and I'm in Directory "x"
now I would love to get all files and directories that match the above pattern.
For example if I'm in
d:\test\test1
valid results would be: (lets assume the folders and files do exist)
d:\test\test1\your_magic.txt.zip
d:\test\test1\your_magic.txtzip
d:\test\test2\your_magic.txt.zip
d:\test\test1\test3\your_magic.txt.zip
What I'm thinking, is that I would need to split up the string into folders and search all of them recursively. Now I'm not a c# pro and hope that there will be a much more simple solution.
See Directory.GetFiles:
string[] files = Directory.GetFiles(#"d:\test", "your_magic*.txt*zip", SerachOption.AllDirectories);

Find files whose path ends with certain pattern

Given a file is in C drive, and its path ends with "Framework64\v4.0.30319\WPF\Fonts\GlobalMonospace.CompositeFont", what is the most efficient way to find the file?
It may be able to find, for example, "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\WPF\Fonts\GlobalMonospace.CompositeFont".
I can implement it in C# or AutoHotKey. I think Directory.EnumerateFiles and loop directive will work, but what is the most efficient way?
Use Directory.EnumerateDirectories with option SearchOption.AllDirectories to find all directories. Then pick those whose path ends in "Framework64\v4.0.30319\WPF\Fonts". Then for those, check whether the file "GlobalMonospace.CompositeFont" exists in those directories using File.Exists.
Loop, C:\*Framework64\v4.0.30319\WPF\Fonts\GlobalMonospace.CompositeFont, , 1 ; recurse into subfolders
{
MsgBox, 4, , Filename = %A_LoopFileFullPath%
continue?
IfMsgBox, No
break
}
https://autohotkey.com/docs/commands/LoopFile.htm

Get all file names in a directory ignoring file extension

I have a folder with files like this:
foo.map
foo.ind
foo.dat
bar.map
bar.ind
bar.dat
readme.txt
readme.html
I like to get all distinct file names but without extension, i.e. foo, bar, readme.
Of course I can use Directory.GetFiles() and make a loop with Path.GetFileNameWithoutExtension() but I wonder if there is a short way, maybe just one line, e.g. using LINQ?
How about:
directory
.GetFiles()
.Select(f => Path.GetFileNameWithoutExtension(f.Name))
.Distinct();

How to GetFiles from multiple different paths

Can we get files from different location using some Built-In Function in C# without any loop. Like if I have following paths
C:\Folder1
C:\abc\Folder2
D:\Folder3
I want to get all files from Folder1, Folder2 and Folder3 at same time without using any loop.
According to MSDN, you can search for files in a single directory.
For example:
Directory.GetFiles("C:\Folder1")
You just need to adapt, however an extension method is not possible since it's a static class.
More info here: http://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx
Basiccly, it means that a loop is required to do search for all the paths. Otherwise, it's not possible.
A loop is required there is no built-in function for that.
You can maintain List<string> for the purpose.
Example:
List<string> lstPaths = new List<string>();
lstPaths.Add(#"C:\Folder1");
lstPaths.Add(#"C:\abc\Folder2");
lstPaths.Add(#"D:\Folder3");
foreach(string sPath in lstPaths)
{
string[] arrFiles = Directory.GetFiles(sPath);
//you can loop through arrFiles here
}

Categories