File Search with specific Extension - c#

How can i search for files with particular extension, the search should be carried out through all the logical drives availbale in my computer.
i tried like
var di = new Directoryinfo(" somepath");
Files = di.GetFiles("*.txt");
But my problem is search should carried out in Each and every folder.
Thank you,

Doesn't DirectoryInfo.GetFiles() contain an overload which has 'recursive/include subfolders'
http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.getfiles.aspx
Looks like it!

Use
List<string> lst = new List<string>();
foreach(var drive in DriveInfo.GetDrives())
{
if(drive.DriveType == DriveType.Fixed)
lst.Concat(Directory.GetFiles(drive.RootDirectory.FullName, "*.txt",
SearchOption.AllDirectories).ToList());
}
Note: If you find files in all directories, it can give you Access Denied error.

Files = di.GetFiles("*.txt", SearchOption.AllDirectories);

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
}

Copy Specific file type from subfolders

I am new to C# and I am trying to build a console application to copy a specific file type .e.g *.txt that is nested within subfolders to be copied to another directory.
The directory looks something like this
C:\V1.1\Folder_*\Folder\Folder\Folder\Filetype.txt
* meaning today's date
How would I get a list of files matching that pattern?
Try something like this.
var path = String.Format(#"C:\V1.1\Folder_{0}\Folder\Folder\Folder",
DateTime.ToString("dd-MM-yyyy"))
DirectoryInfo di = new DirectoryInfo(path);
var files=di.GetFiles("*.txt", SearchOption.AllDirectories)
You can check this site out for more information.
Thanks for all the help. I ended up doing this:
foreach (var file in Directory.GetFiles(sourceDir, "*.txt", SearchOption.AllDirectories))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)), true);

Want to list all Image Files in a folder using C# [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
GetFiles with multiple extentions
is there a function like GetFiles that takes more then 1 file type like
DirectoryInfo di = new DirectoryInfo("c:/inetpub/wwwroot/demos");
FileInfo[] rgFiles = di.GetFiles("*.bmp, *.jpg, etc");
AFAIK, this isn't directly possible.
Instead, you can get every file, then filter the array:
HashSet<string> allowedExtensions = new HashSet<string>(extensionArray, StringComparer.OrdinalIgnoreCase);
FileInfo[] files = Array.FindAll(dirInfo.GetFiles(), f => allowedExtensions.Contains(f.Extension));
extensionArray must include . before each extension, but is case-insensitive.
Not that I know of.
I implemented the same problem like so:
DirectoryInfo di = new DirectoryInfo("c:/inetpub/wwwroot/demos");
FileInfo[] rgFiles = di.GetFiles("*.bmp")
.Union(di.GetFiles("*.jpg"))
.Union(di.GetFiles("etc"))
.ToArray();
Note that this requires the System.Linq namespace.
How to get files with multiple extensions
If you want your code to be bullet proof in the sense your file detection mechanism detects an image file not based on the extension but on the nature of the file, you'd have to to load your files as byte[] and look for a magic trail of bytes usually in the beginning of the array. Every graphical file has it's own way of manifesting itself to the software through presenting that magic value of bytes. I can post some code examples if you'd like.
No, theres not. Windows does not have a way to separate filters in the search pattern.
This could be done manually through LINQ, though.
By using the EnumerateFiles you'll get results as they come back so you don't have to wait for all the files in order to start working on the result.
var directory = new DirectoryInfo("C:\\");
var allowedExtensions = new string[] { ".jpg", ".bmp" };
var imageFiles = from file in directory.EnumerateFiles("*", SearchOption.AllDirectories)
where allowedExtensions.Contains(file.Extension.ToLower())
select file;
foreach (var file in imageFiles)
Console.WriteLine(file.FullName);

Searching for a file with C#

What would be the fastest way to search for a file programtically in C#. I know the relative location of the file, lets say its "abcd\efgh\test.txt". I also know that this file is on my E:\ drive. "abcd" is a subdirectory on some directory in E:\ drive.
Thanks
Since you know the root directory you want to search and a string pattern for a filename, you can create a DirectoryInfo with the root directory:
DirectoryInfo dir = new DirectoryInfo(#"E:\");
And then call GetFiles() to get all the matches. Passing SearchOption.AllDirectories will ensure the search is recursive.
List<FileInfo> matches =
new List<FileInfo>(dir.GetFiles(partialFilename,
SearchOption.AllDirectories));
Or if you know part of the path (instead of the filename):
List<DirectoryInfo> matches =
new List<DirectoryInfo>(dir.GetDirectories(partialDirectoryName,
SearchOption.AllDirectories));
And then you can navigate to the file from there.
So if I understand correctly you know the path will be of the form:
"E:\\" + something + "\\abcd\\efgh\\test.txt"
If something is only 1 level deep, then simply get all directories on your E:, and then try to do a file open on each of those subdirectories.
If something is more than 1 level deep, then do a recursive call to get the directories until you find abcd.
The fastest way would probably be to use FindFirstFile etc api but I would have thought that you could do it fairly quickly (And much easier) with Directory.GetDirectories (to find the right sub direcotry) and then Directory.GetFiles to find the actual file.
Just the use File.Exists method and iterate through all possible filenames. Maybe something like this (not tested):
string SearchInFolder(string root) {
if (File.Exists(Path.Append(root, "\\abcd\\efgh\\test.txt")) return Path.Append(root, "\\abcd\\efgh\\test.txt");
foreach(var folder in Directory.GetDirectories(root)) {
var fullFile = Path.Append(folder, "\\abcd\\efgh\\test.txt");
if (File.Exists(fullFile)) {
// Found it !!!!
return fullFile;
} else {
var result = SearchInFolder(folder);
if (result != null) return result;
}
}
return null;
}
But this will seach the whole E:\ drive for the pattern, also subfolders are searched.
I think the algorithm would be start at e:\ and read all directories. If one of them is \abcd\, immediately check for the rest of the path and file, e.g., efgh\test.txt.
If e:\ does NOT have \abcd\, then you need to traverse into each subdirectory and do the same check. Does \abcd\ exist? Yes, check for efgh\text.txt. No? Traverse subdirs.
If you need the absolutely fastest, when you fail to find \abcd\, and you have your list of subdirs you must now go check, you could introduce some level of threading. But that could get hairy rather quickly.

DirectoryInfo.getFiles beginning with

I've come across some strange behavior trying to get files that start with a certain string.
Please would someone give a working example on this:
I want to get all files in a directory that begin with a certain string, but also contain the xml extension.
for example:
apples_01.xml
apples_02.xml
pears_03.xml
I want to be able to get the files that begin with apples.
So far I have this code
DirectoryInfo taskDirectory = new DirectoryInfo(this.taskDirectoryPath);
FileInfo[] taskFiles = taskDirectory.GetFiles("*.xml");
FileInfo[] taskFiles = taskDirectory.GetFiles("apples*.xml");
var taskFiles = taskDirectory.GetFiles("*.xml").Where(p => p.Name.StartsWith("apples"));

Categories

Resources