Directory.Getfiles
i want to do a search for all textfiles in C:\ so i did this
ListBox1.Items.AddRange(IO.Directory.GetFiles("C:\", "*.txt", IO.SearchOption.AllDirectories))
but i get an error saying "Access to the path C:\system vloume information is denied", if it was in a loop i could say on error resume next but with this you cant, is there any other way around it ?
thanks.
string[] dirs = Directory.GetDirectories("c:\\"); Make a string array called dirs that contains all of the directories located in c:\\
foreach (String d in dirs) go through dirs and take one string at a time from it and do the following to that string
{
if (d != "c:\\System Volume Information") if the string is not equal to the string "c:\\System Volume Information" then do the following
listBox1.Items.AddRange(Directory.GetFiles (d, "*.txt", SearchOption.AllDirectories)); looks like you add the files from the directory you looked at in the above if statement and get all the files that end in ".txt" from anywhere inside this directory. You then add these items to a listbox called listBox1
} when you hit here you are done going through each directory name in dirs
listBox1.Items.AddRange(Directory.GetFiles("c:\\", "*.txt")); looks like you add the files from the directory c:\\ that end in ".txt" to the list box listbox1'
Don't know if this translation will help anyone, but this is the best I can do.
~Lauren
Well I'll be a son-of a -gun.
We were having this same discussion in a different thread the other day and nobody knew how to get around the 'start search at root level' errors.
Me, the guy who does not know C, translated the example C and it worked like a charm. What is the extra '\' after 'C:' all about? Anyway, this seems to work...
Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim dirs As String() = IO.Directory.GetDirectories("c:\\") For Each d As String In dirs If d <> "c:\\System Volume Information" Then ListBox1.Items.AddRange(IO.Directory.GetFiles(d,
"*.txt", IO.SearchOption.AllDirectories)) ListBox1.Items.AddRange(IO.Directory.GetFiles(
"c:\\", "*.txt")) End If Next End Sub 1 year later...
The extra \ (C:\ to C:\\) is because \ is an escape character. For example:
"C:\\No problem" would be the string:
"C:\No problem" (\\ -> \)
"C:\No problem" would be:
"C:
o problem" (\n -> line break)
because \n is considered 1 character which means a new line. To get around this, use an @ symbol in front of the string:
@"C:\No problem" would be
"C:\No problem"
The @ symbol ignores any escape characters and will take every single character (including new lines) into the string. This can be really useful but also a bit of a pain.