how to search media file in our system by c#? - c#

I want to search the media files situated in my system by c#. means I want to create the search engine that will scan all drives (again small question here , how to get the drives on our system by c# code ? )and search the media files like .mp3,.mp4,...etc . How can i do that by c# desktop application?

try this:
List<string> mediaExtensions = new List<string>{"mp3", "mp4"};
List<string> filesFound = new List<string>();
void DirSearch(string sDir)
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, "*.*"))
{
if(mediaExtensions.Contains(Path.GetExtension(f).ToLower()))
filesFound.Add(f);
}
DirSearch(d);
}
}

Rather than a brute-force iterative search through directories, I recommend looking into using the Windows Desktop Search API, which will be orders of magnitude faster.
Windows Desktop Search via C#

To get your drive list:
string[] drives = Environment.GetLogicalDrives();
To get all your files:
foreach(string drive in drives)
string[] allFiles = Directory.GetFiles(drive, "*.*", SearchOption.AllDirectories);
To get all your files using recursion:
List<string> allFiles = new List<string>();
private void RecursiveSearch(string dir)
{
allFiles.Add(Directory.GetFiles(dir));
foreach(string d in Directory.GetDirectories(dir))
{
RecursiveSearch(d);
}
}
Filter using Manu's answer

try this
var files = new List<string>();
//#Stan R. suggested an improvement to handle floppy drives...
//foreach (DriveInfo d in DriveInfo.GetDrives())
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady == true))
{
files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "File Name", SearchOption.AllDirectories));
}

Related

winrt how to get files list from device using c#

I need get a list of all files in device (phone or PC) in my universal app. In wpf I did somesing like that:
class Collection {
private StringCollection seachResults;
//find all mp3 files in local storage
private void ScanDrives() {
seachResults.Clear();
string[] drives = Environment.GetLogicalDrives();
foreach (string dr in drives) {
DriveInfo di = new DriveInfo(dr);
if (!di.IsReady) {
//skip if drive not ready
continue;
}
DirectoryInfo rootDir = di.RootDirectory;
WalkDirectoryTree(rootDir);
}
}
private void WalkDirectoryTree(DirectoryInfo root) {
FileInfo[] files = null;
DirectoryInfo[] subDirs = null;
try {
files = root.GetFiles("*.mp3");
} catch (UnauthorizedAccessException e) {
} catch (DirectoryNotFoundException e) {
}
if (files != null) {
foreach (FileInfo fileInfo in files) {
seachResults.Add(fileInfo.FullName);
}
subDirs = root.GetDirectories();
foreach (DirectoryInfo dirInfo in subDirs) {
WalkDirectoryTree(dirInfo);
}
}
}
}
But when I try to migrate this into winRT app I get a few errors like unknown type Drive and unexisted method Environment.GetLogicalDrives().
Can anyone say how do that in winRT?
You won’t find a method for getting all logical drives in a WinRT app; WinRT apps exist in a sandboxed environment and will only have access to their own isolated storage or known folders (such as music) if declared as a capability in the application manifest.
For example, to get access to the user’s music folder you can do this (don’t forget to declare the capability in the app manifest):
StorageFolder folder = Windows.Storage.KnownFolders.MusicLibrary;
The only way to get access to any other part of the file system is if the user specifically grants access via a file picker:
var folderPicker = new FolderPicker();
var folder = await folderPicker.PickSingleFolderAsync();
Have you tried System.IO.Directory.GetLogicalDrives()?
I believe that Environment.GetLogicalDrives() only works for Win32/Win64. If I am not mistaken System.IO.Directory exists in mscorlib, and is widely available across Phone, RT, or Regular versions.
The MSDN reference:
https://msdn.microsoft.com/en-us/library/system.io.directory.getlogicaldrives%28v=vs.110%29.aspx

getfiles is ignoring current user folder?

The folder C:\Users contain 3 subfolders :
C:\Users\hacen
C:\Users\_rafi_000
C:\Users\Public
However, when I call :
DirSearch(#"C:\Users\", "*.jpg");
It outputs all jpg filenames from Public and hacen, but not from _rafi_000 which is the folder of current user.
Here is the function :
static void DirSearch(string dir, string pattern)
{
try
{
foreach (string f in Directory.GetFiles(dir, pattern))
{
Console.WriteLine(f);
}
foreach (string d in Directory.GetDirectories(dir))
{
DirSearch(d, pattern);
}
}
catch (System.Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
EDIT:
I tried with the code below and it works. So it isn't an access denied problem :
DirSearch("C:\Users\_rafi_000\","*.jpg");
What I noticed so far is that unlike other subfolders, the folder _rafi_000 cannot be ranamed when I press F2
Would this work?
void DirSearch(string dir, "*.JPG")
{
foreach (string f in Directory.GetFiles(dir, "*.JPG"))
{
Console.WriteLine(f);
}
foreach (string d in Directory.GetDirectories(dir))
{
DirSearch(d);
}
}
Could be related to where the jpg are stored and how reparse points work in later windows version.
I suggest looking at:
Directory Searching: http://msdn.microsoft.com/en-us/library/bb513869.aspx
Reparse Point Info: http://msdn.microsoft.com/en-us/library/aa365503(VS.85).aspx
I ran your code and it works fine in windows XP:
C:\Users\hacen\bar.jpg
C:\Users\Public\bar1.jpg
C:\Users\_rafi_000\bar2.jpg
Your code is correct.
Perhaps Process Monitor can help?
If the code is fine, it must be something else. I understand that you can run the code directly against the directory which is causing you a problem (which is surprising) - but I think Process Mon could help.

Crawling a directory

I have this test path:
private static string dCrawler = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "TestLetters";
Is there a way to say:
foreach (item in dCrawler)
{
if (item.isFile)
{
// check file info date modified code
} else
{
foreach (fileinfo file in ...
}
}
so far I have only found ways to check a file in a directory. Is the only way to do it by having two separate loops one for files and one for folders?
You can use Directory.GetFiles(); that returns a string[] and use the string value to create your FileInfo. Like this
foreach (string n in Directory.GetFiles(dCrawler))
{
FileInfo b = new FileInfo(n);
}
To get directories, you can similarly use Directory.GetDirectories();
foreach (string n in Directory.GetDirectories(dCrawler))
{
DirectoryInfo b = new DirectoryInfo(n);
}

How can I perform full recursive directory & file scan?

here is my code:
private static void TreeScan(string sDir)
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d))
{
//Save file f
}
}
TreeScan(d, client);
}
The problem is that it doesn't get the FILES of the sDir (Starting Directory) it only gets the Folders and the Files in the Sub Folders.
How can I make it get the files from the sDir too ?
Don't reinvent the wheel, use the overload of GetFiles that allows you to specify that it searches subdirectories.
string[] files
= Directory.GetFiles(path, searchPattern, SearchOption.AllDirectories);
private static void TreeScan( string sDir )
{
foreach (string f in Directory.GetFiles( sDir ))
{
//Save f :)
}
foreach (string d in Directory.GetDirectories( sDir ))
{
TreeScan( d );
}
}
There are some problems with your code. For one, the reason you never saw the files from the root folder is because your recursed before doing and file reads. Try this:
public static void Main()
{
TreeScan(#"C:\someFolder");
}
private static void TreeScan(string sDir)
{
foreach (string f in Directory.GetFiles(sDir))
Console.WriteLine("File: " + f); // or some other file processing
foreach (string d in Directory.GetDirectories(sDir))
TreeScan(d); // recursive call to get files of directory
}
You have to use
Directory.GetFiles(targetDirectory);
like in This sample, wich contains a complete implementation of what you're looking for
Your GetFiles loop should be outside the GetDirectories loop. And shouldn't your TreeScan stay inside GetDirectories loop? In short the code should look like this:
private static void TreeScan(string sDir)
{
foreach (string d in Directory.GetDirectories(sDir))
{
TreeScan(d, client);
}
foreach (string f in Directory.GetFiles(d))
{
//Save file f
}
}
If using Fx4 and above the EnumerateFiles method will return all files with efficient memory management, whereas GetFiles can require max resources on big directories (or drives).
var files = Directory.EnumerateFiles(dir.Path, "*.*");

Solving UnauthorizedAccessException issue for listing files

Listing all files in a drive other than my system drive throws an UnauthorizedAccessException.
How can I solve this problem?
Is there a way to grant my application the access it needs?
My code:
Directory.GetFiles("S:\\", ...)
Here's a class that will work:
public static class FileDirectorySearcher
{
public static IEnumerable<string> Search(string searchPath, string searchPattern)
{
IEnumerable<string> files = GetFileSystemEntries(searchPath, searchPattern);
foreach (string file in files)
{
yield return file;
}
IEnumerable<string> directories = GetDirectories(searchPath);
foreach (string directory in directories)
{
files = Search(directory, searchPattern);
foreach (string file in files)
{
yield return file;
}
}
}
private static IEnumerable<string> GetDirectories(string directory)
{
IEnumerable<string> subDirectories = null;
try
{
subDirectories = Directory.EnumerateDirectories(directory, "*.*", SearchOption.TopDirectoryOnly);
}
catch (UnauthorizedAccessException)
{
}
if (subDirectories != null)
{
foreach (string subDirectory in subDirectories)
{
yield return subDirectory;
}
}
}
private static IEnumerable<string> GetFileSystemEntries(string directory, string searchPattern)
{
IEnumerable<string> files = null;
try
{
files = Directory.EnumerateFileSystemEntries(directory, searchPattern, SearchOption.TopDirectoryOnly);
}
catch (UnauthorizedAccessException)
{
}
if (files != null)
{
foreach (string file in files)
{
yield return file;
}
}
}
}
You can the use it like this:
IEnumerable<string> filesOrDirectories = FileDirectorySearcher.Search(#"C:\", "*.txt");
foreach (string fileOrDirectory in filesOrDirectories)
{
// Do something here.
}
It's recursive, but the use of yield gives it a low memory footprint (under 10KB in my testing). If you want only files that match the pattern and not directories as well just replace EnumerateFileSystemEntries with EnumerateFiles.
Are you allowed to access the drive? Can the program access the drive when it's not run from Visual Studio? Are restrictive permissions defined in the project's Security page ("Security Page, Project Designer")?
In .net core you can do something like this below. It can search for all subdirectories recursively with good performance and ignoring paths without access.
I also tried other methods found in
How to quickly check if folder is empty (.NET)? and
Is there a faster way than this to find all the files in a directory and all sub directories? and
https://www.codeproject.com/Articles/1383832/System-IO-Directory-Alternative-using-WinAPI
public static IEnumerable<string> ListFiles(string baseDir)
{
EnumerationOptions opt = new EnumerationOptions();
opt.RecurseSubdirectories = true;
opt.ReturnSpecialDirectories = false;
//opt.AttributesToSkip = FileAttributes.Hidden | FileAttributes.System;
opt.AttributesToSkip = 0;
opt.IgnoreInaccessible = true;
var tmp = Directory.EnumerateFileSystemEntries(baseDir, "*", opt);
return tmp;
}
I solved the problem. Not really but at least the source.
It was the SearchOption.AllDirectories option that caused the exception.
But when I just list the immediate files using Directories.GetFiles, it works.
This is good enough for me.
Any way to solve the recursive listing problem?

Categories

Resources