Searching and copying Sub Directories in C Sharp - c#

I am currently writing a program which searches My Documents. Currently my program is able to search and copy the main my documents folder but I am unable to make it search sub directory's within the main my documents directory. I have tried multiple methods but none seem to be working out.
Currently I am using the below code to dump the files location into an array called files. sourcePath is declared in an array before hand.
string[] files = System.IO.Directory.GetFiles(sourcePath[loopcounter]);
I then have a loop which copy's the files over to another directory
foreach (string s in files)
Any help as to how to fill the array files with details of files in the sub directories of a folder would be very handy. Thanks in advance!

Use research by pattern and specify you want use recursion :
var allFiles = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"*",
SearchOption.AllDirectories);
foreach (var item in allFiles)
{
// Do Stuff...
}

If you want details about each file, then GetFiles returns you array of names. Pass each name to FileInfo API.

Related

How to iterate through the physical folders and read a leaf file in C#

I have a root node A which contains B which contains C which contains D which contains an XML file abc.xml
So in D:\ drive ,I have the following structure of directories A>>B>>C>>D.
This path is dynamic. What is the best practice to read the file abc.xml in C# by iterating through the physical folders?
You could implement a recursive search algorithm that goes through all the folders and descends into the sub folders.
Pseudo Code:
public void GetXMLFilesRecursive(string currentFolder, List<string> results)
{
// Enumerate all directories of currentFolder
string[] folders = Directory.GetDirectories(currentFolder);
foreach (string folder in folders)
GetXMLFilesRecursive(folder, results));
// Enumerate all XML files in this folder only if it has no other sub-folders (is a leaf)
if (folders.Length == 0)
{
string[] xmlFiles = Directory.GetFiles(currentFolder, "*.xml");
results.AddRange(xmlFiles);
}
}
This method only returns XML files in the lowest folders of the hierarchy (i.e. folders that don't have sub folders). If you want all files you find along the way, comment out if (folders.Length == 0). On the other hand, you could then also use Directory.GetFiles with SearchOption.AllDirectories.
Why I wrote a recursive algorithm: The OP asked how to find all XML files in the leaf directories. You can not do that using Directory.GetFiles with SearchOption.AllDirectories, but you then need to implement the above.
You can use Directory.GetFiles(d, "*.xml",SearchOption.AllDirectories) to get all the xml files get what you are looking for.
You can search an entire tree for a file using Directory.GetFiles(path,searchPattern,SearchOption) or Directory.EnumerateFiles with SearchOption.AllDirectories, eg
var fullPaths=Directory.GetFiles(myPath,"abc.xml",SearchOption.AllDirectories)
You can also use the DirectoryInfo class to get full FileInfo instances instead of just the paths, with access to file properties and attributes:
var myDir=new DirectoryInfo(myPath);
var fileInfos=myDir.GetFiles("abc.xml",SearchOption.AllDirectories);
The difference between the GetFiles and EnumerateFiles methods is that the first returns an array with all the files found, blocking until it finds all of them. EnumerateFiles on the other hand returns results as it finds them, so you get to process the results much sooner.
What goes for GetFiles goes for the GetDirectories/EnumerateDirectories set of functions as well. The methods are available both from the Directory and DirectoryInfo class.
If you want to search for both directories and files, you can use GetFileSystemEntries/EnumerateFileSystemEntries to return both of them with a single call. The equivalent DirectoryInfo methods are GetFileSystemInfos/EnumerateFileSystemInfos
public List<string> getFiles(string path, string searchPattern, List<string> list)
{
try
{
foreach (string folder in Directory.GetDirectories(path))
getFiles(folder, searchPattern, list);
list.AddRange(Directory.GetFiles(path, searchPattern));
}
catch (UnauthorizedAccessException)
{
//Do not have access to the file.
}
return list;
}
Call like this:
//Get all xml files in the D drive:
List<string> files = getFiles(#"d:\", "*.xml", new List<string>());

Read all text files in a folder with StreamReader

I am trying to read all .txt files in a folder using stream reader. I have this now and it works fine for one file but I need to read all files in the folder. This is what I have so far. Any suggestions would be greatly appreciated.
using (var reader = new StreamReader(File.OpenRead(#"C:\ftp\inbox\test.txt")))
You can use Directory.EnumerateFiles() method instead of.
Returns an enumerable collection of file names that match a search
pattern in a specified path.
var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt");
foreach (string currentFile in txtFiles)
{
...
}
You can call Directory.EnumerateFiles() to find all files in a folder.
You can retrieve the files of a directory:
string[] filePaths = Directory.GetFiles(#"c:\MyDir\");
Therefore you can iterate each file performing whatever you want. Ex: reading all lines.
And also you can use a file mask as a second argument for the GetFiles method.
Edit:
Inside this post you can see the difference between EnumerateFiles and GetFiles.
What is the difference between Directory.EnumerateFiles vs Directory.GetFiles?

populating datagridview with files in multiple subfolderse

I'm confronted with a design problem in my attempt to populate my datagridview with simple files.
I've declared a main directory in my Settings file. I need my datagridview to search through this parent directory in 7 subfolders. Each subfolder has a bunch of subfolders (names of machines I am managing). Each of those has contained in it the file I need to add to my grid.
Example:
C:\Users\me\Documents\MASTERDIRECTORY\Folder7\Machine Name1\file.txt
C:\Users\me\Documents\MASTERDIRECTORY\Folder7\Machine Name2\file.txt
Obviously some kind of recursive code is needed to perform the search, but how should I start? Performance wise, should I add these file paths to an array list and then translate that to my grid?
Something like this may help :-
string filePath = #"C:\Users\me\Documents\MASTERDIRECTORY\Folder7"
foreach (string Folder in Directory.GetDirectories(filePath))
{
foreach (string file in Directory.GetFiles(Folder))
{
// here you can grab the log file path and add it to you Gridview
}
}

How do I search for files using C# on a windows OS

I have a csv file with file names and I need to search for those filenames in a particular directory. I can read thru a csv file and get all the filenames but would like to know how can I search for those files.
Any pointers would be would of great help
What about trying following code snippet.
Directory.EnumerateFiles(directory, fileName, SearchOption.AllDirectories);
System.IO.Directory.Getfiles will give you a list of files in a particular directory. If you need to so more intensive searching. You may want to use the windows indexing.
It's pretty easy, there are many different ways you can do this. I prefer the "exists" method if I am just trying to find out if the files are there.
string SearchDirectory = "C:\\SomeDirectory\\";
List<String> FilesToSearch = new List<string>();
//Populate FilesToSearch from your csv...
foreach (String CurrentFileToSearch in FilesToSearch)
{
if (System.IO.File.Exists(SearchDirectory + TargetFileName))
{
//Do Something!
}
}

Recursive iteration in C#

I have a custom object that contains methods that returns all directory and file names in a root
string[] dirlist = obj.GetDirectories();
//which returns all dir names in root
string[] filelist = obj.GetFiles();
//which return all file names in root
I cannot modify these methods. Once I get the dirlist, how do i get a list of all subdirs in it as well as files in the subdirs, ignoring the security exceptions. It can be nested to multiple levels. Anything in .NET 4?
Update: string[] dirList can also be read as List dirlist. Please give a solution that uses the latest features of .NET
DirectoryOne
- SubDirOne
- SubDirTwo
- FileOne
- FileTwo
- SubDirThree
DirectoryTwo
DirectoryOne
There are already built-in .NET methods to do this:
// get all files in folder and sub-folders
Directory.GetFiles(path, "*", SearchOption.AllDirectories);
// get all sub-directories
Directory.GetDirectories(path, "*", SearchOption.AllDirectories);
Somehow I get the feeling this isn't the solution you're looking for though.
Update:
I think I may know what you're trying to ask, since you tagged it as LINQ. If you want to get a list of all sub-directories and sub-folders given a list of directories, you can use the following code:
// get all files given a collection of directories as a string array
dirList.SelectMany(x => Directory.GetFiles(x, "*", SearchOption.AllDirectories));
// get all sub-directories given a collection of directories as a string array
dirList.SelectMany(x => x.Directory.GetDirectories(x, "*", SearchOption.AllDirectories));
Have a look at the Directory Class
foreach(string dir in Directory.GetDirectories("c:\","",SearchOption.AllDirectories))
{
Console.Writeline(dir);
foreach(string file in Directory.GetFiles(dir))
{
Console.Writline(file);
}
}
This will print all directories under C:\ and then all the files in each of those directories.
Does that help?

Categories