getfiles is ignoring current user folder? - c#

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.

Related

Ignore folder C# (System.UnauthorizedAccessException)

A quick question. I'm executing this code:
listBox1.Items.AddRange( Directory.GetDirectories("C:\\Users\\", "*" ,SearchOption.AllDirectories));
It list all directories and subdirectories in C:\Users\ (yes I know, it maybe blow up my pc)
Anyways, I am getting this error (System.UnauthorizedAccessException)
This error comes from the special folders "C:\Users\All Users\" and "C:\Users\USER\AppData\"
How can I ignore this folders to program keeping listing all dir and subd without Exceptions?
Unfortunately it's not possible to filter out all directories without the required permissions. You need to implement your own recursive function to deal with the problem by catching the UnauthorizedAccessException. Since there could be many exceptions the way is not very fast but reliable like explained in this question:
[...] permissions (even file existence) are volatile — they can change at any time [...]
Here is my possible solution:
public static void GetDirectories(string path, Action<string> foundDirectory)
{
string[] dirs;
try
{
dirs = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
catch (UnauthorizedAccessException)
{
//Ignore a directory if an unauthorized access occured
return;
}
foreach (string dir in dirs)
{
foundDirectory(dir);
//Recursive call to get all subdirectories
GetDirectories(dir, foundDirectory);
}
}
Simply call the function like
List<string> allDirectories = new List<string>();
GetDirectories(#"C:\Users\", d => allDirectories.Add(d));

Search for ".myox" files on Computer

trying to write a small windows application for my company. the part i am stuck at the moment is trying to search the computer for ".myox" files (or say any file type). Below pasted is the code i have worked out. I am an amateur programmer trying to get started with coding. The issue am having at the moment with the code below is its skipping almost all locations on the computer with the exception coming up as "access denied". I have run the VS as admin, and i am an admin on the computer as well. Not sure what i am missing, but if someone can point me in the right direction, that would be amazing.
private void FindAllFiles()
{
int drvCount;
int drvSearchCount = 0;
DriveInfo[] allDrives = DriveInfo.GetDrives();
drvCount = allDrives.Count();
foreach (DriveInfo dr in allDrives)
{
lbAllFiles.Items.Clear();
drvSearchCount++;
//removable drives
if (!dr.IsReady)
break;
foreach (string dir in Directory.GetDirectories(dr.ToString()))
{
try
{
foreach (string files in Directory.GetFiles(dir, "*.myox"))
{
lbAllFiles.Items.Add(files);
}
}
catch (Exception Error)
{
}
}
if (drvSearchCount == drvCount)
break;
}
MessageBox.Show("Done searching your computer");
}
Thanks in Advance.
-Manu
I see few "potential" issues and will list them below.
First is that you're doing this on main ( UI ) thread which will block whole application giving you no feedback about current state. You can use Thread to get rid of this problem. Outcome from this operation will produce another issue which is accessing lbAllFiles because ( as i think ) it's part of the UI. You can easily get rid of this problem making a List<string> that can be filled during FindAllFiles operation and then assigned into lbAllFiles.Items.
Second issue is :
foreach (string files in Directory.GetFiles(dir, "*.myox"))
{
lbAllFiles.Items.Add(files);
}
Directory.GetFiles(...) will return only the files that are matching your pattern parameter so you can simply do :
var files = Directory.GetFiles(dir, "*.myox");
if ( files != null && files.Length > 0 )
lblAllFiles.Items.AddRange(files);
And finaly to get ( or check ) permission you can Demand() permissions as I've posted in the comment :
foreach (string dir in Directory.GetDirectories(dr.ToString()))
{
FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Read, dir);
try
{
permission.Demand();
var files = Directory.GetFiles(dir, "*.myox");
if ( files != null && files.Length > 0 )
lblAllFiles.Items.AddRange(files);
}
catch (Exception Error)
{
}
}
Let me know if that helped you. If not I'll try to update my answer with another solution.
One thing i noticed in your code, is that you're not navigating through ALL directories and sub-directories. For that, where you call the GetDirectories function, not only send the path, but use the enumerator Alldirectories:
foreach (string dir in Directory.GetDirectories(dr.ToString(),System.IO.SearchOption.AllDirectories))

C# - How to recursively search a directory in a WPF application?

I can do this task in a normal form application but i am brand new to working with WPF applications.
I want to enter a directory path in a TextBox, then click a Button which validates and recursively searches that path, and displays all the files in a ListBox.
I have already looked at this article but i don't understand it fully because again, i'm very new to this.
Any help would be appreciated.
Try this.
DirectoryInfo dir = new DirectoryInfo("your path");
dir.GetFiles("*.*", SearchOption.AllDirectories);
Or this;
void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, txtFile.Text))
{
lstFilesFound.Items.Add(f);
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}

how to open all *.xml files on my computer by my C# program?

i made C# program that open and show xml files.
how to make (on my program installation) that all *.xml files
that in my computer will opened with my program ?
thanks in advance
As detailed in this question, you need to change the value of the registry key HKEY_CLASSES_ROOT\xmlfile\shell\open\command on the user's machine.
This could be achieved programatically by code such as (untested):
// Get App Executable path
string appPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
RegistryKey rkShellOpen = Registry.ClassesRoot.OpenSubKey(#"xmlfile\shell\open", true);
rkShellOpen.SetValue("command", appPath);
I think he is wanting a way to search the hard drive for all xml files, so that he can then manage them in some sort of tree for easy opening and closing.
You could do something similar to this...
void RecursiveDirectorySearch(string sDir, string patternToMatch)
{
// Where sDir would be the drive you want to search, I.E. "C:\"
// Where patternToMatch has the extension, I.E. ".xml"
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, txtFile.Text))
{
if(f.Contains(patternToMatch)
{
lstFilesFound.Items.Add(f);
}
}
DirSearch(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}

list recursively all files and folders under the given path? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to recursively list all the files in a directory in C#?
I want to list the "sub-path" of files and folders for the giving folder (path)
let's say I have the folder C:\files\folder1\subfolder1\file.txt
if I give the function c:\files\folder1\
I will get
subfolder1
subfolder1\file.txt
You can use the Directory.GetFiles method to list all files in a folder:
string[] files = Directory.GetFiles(#"c:\files\folder1\",
"*.*",
SearchOption.AllDirectories);
foreach (var file in files)
{
Console.WriteLine(file);
}
Note that the SearchOption parameter can be used to control whether the search is recursive (SearchOption.AllDirectories) or not (SearchOption.TopDirectoryOnly).
Try something like this:
static void Main(string[] args)
{
DirSearch(#"c:\temp");
Console.ReadKey();
}
static void DirSearch(string dir)
{
try
{
foreach (string f in Directory.GetFiles(dir))
Console.WriteLine(f);
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(d);
DirSearch(d);
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
String[] subDirectories;
String[] subFiles;
subDirectories = System.IO.Directory.GetDirectories("your path here");
subFiles = System.IO.Directory.GetFiles("your path here");
Use the System.IO.Directory class and its methods
I remember solving a similar problem not too long ago on SO, albeit it was in VB. Here's the question.

Categories

Resources