C# retrieving subdirectories from selected directory - c#

I am trying to find a way to retrieve the subfolders from a selected directory. I have used FolderBrowserDialog inside of my code to all the user to select the "root" directory that the program will be using. But I am stuck on how to get the subdirectories from that. I want to plce these subdirectory string names inside an array to be used later. I tried using Directory.getFiles("the selected path"), but this does not display the subdirectories.
Any help is greatly appreciated! Thank you
private void Folderselector_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
listView1.Items.Clear();
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string file in files)
{
string fileName = Path.GetFileNameWithoutExtension(file);
ListViewItem item = new ListViewItem(fileName);
item.Tag = file;
listView1.Items.Add(item);
}
}
}

Use the method overload with SearchOption.AllDirectories

something like this?
var dirs = new DirectoryInfo(path).GetDirectories("*",SearchOption.AllDirectories)
.Select(d => d.FullName)
.ToList();
and if you want the directory names relative to your root dir
var dirs = new DirectoryInfo(path).GetDirectories("*",SearchOption.AllDirectories)
.Select(d => d.FullName)
.Select(s => new Uri(path).MakeRelative(new Uri(s)).ToString())
.ToList();

Close, but there's a different method for directories:
System.IO.Directory.GetDirectories(string rootDirectory);

System.IO.Directory.GetDirectories(string rootDirectory);
With recursion is your solution
List<string> dirsResult = new List<string>();
public void GetDirectories(string currentDirectory)
{
string[] directories = Directory.GetDirectories(currentDirectory);
foreach(var dir in directories)
{
dirsResult.Add(dir);
GetDirectories(dir);
}
}
I haven't tested it, but something like this should work.

Related

in c# how to get filenames in dropdown without the full path

I want the list of files in a folder to be populated into my dropdown list.
in c# i use this to get filenames into dropdown:
private void CasparRefresh_Click(object sender, EventArgs e)
{
string[] fileArray = Directory.GetFiles(#"C:\Users\JoZee\Desktop\Energy\Caspar\Server\media\");
foreach (string name in fileArray)
{
cbxV1.Items.Add(name);
}
How to i get only the filenames without the full path
You can use Path.GetFileName() method on the output of Directory.GetFiles()
string[] fileArray = Directory.GetFiles(#"C:\Users\JoZee\Desktop\Energy\Caspar\Server\media\");
foreach (string name in fileArray)
{
cbxV1.Items.Add(Path.GetFileName(name));
}
There is another option to do same:
var dirInfo = new DirectoryInfo(#"C:\Users\JoZee\Desktop\Energy\Caspar\Server\media\");
foreach (var fileInfo in dirInfo.GetFiles())
{
cbxV1.Items.Add(fileInfo.Name);
}

How can I find a file within any description of path?

I need find the specific file/folder on my hard drive.
For example i need find a file (do1.bat) and then store the path of the file. But i dont know where can it be stored, so i have to scan all hard drive.
How can i use C# for this?
A simple way would be
var results = Directory.GetFiles("c:\\", "do1.bat", SearchOption.AllDirectories);
This would recurse through all directory and collect all files named do1.bat. Unfortunatly this will not work on complete c:\ since it will throw exceptions if you don't have access to a directory, which surely will happen.
So this is a recursive version:
private static void FindFile(DirectoryInfo currentDirectory, string pattern, List<FileInfo> results)
{
try
{
results.AddRange(currentDirectory.GetFiles(pattern, SearchOption.TopDirectoryOnly));
foreach (DirectoryInfo dir in currentDirectory.GetDirectories("*", SearchOption.TopDirectoryOnly).Where(d => d.Name != "." && d.Name != ".."))
FindFile(dir, pattern, results);
}
catch
{
// probably no access to directory
}
}
This recurses through the directory tree and tries to get the files in a directory and then all subdirectories (except . and ..).
You can use it this way:
DirectoryInfo d = new DirectoryInfo("c:\\");
List<FileInfo> results = new List<FileInfo>();
FindFile(d, "do1.bat", results);
This will find all files named do1.bat in any subdirectory of C:\\ and enlist the FileInfos in the results list.
this should provide you a list of files, matching your search pattern
string[] Result = Directory.GetFiles(#"C:\", "do1.bat", SearchOption.AllDirectories);
Refer: https://msdn.microsoft.com/en-us/library/07wt70x2(v=vs.110).aspx
List<string> lstfilepaths = new List<string>();
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries) // included as per your logic
{
if(fileName == "do1.bat")
{
ProcessFile(fileName);
}
}
// Recurse into subdirectories of this directory.
string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach(string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
public static void ProcessFile(string path)
{
lstfilepaths.Add(path);
}
For one file:
public string FindFileByName(string fileName, string searchPath)
{
string resultPath = null;
DirectoryInfo directoryInWhichToSearch = new DirectoryInfo(searchPath);
FileInfo foundFile = directoryInWhichToSearch.GetFiles(fileName, SearchOption.AllDirectories)[0];
resultPath = foundFile.FullName;
return resultPath;
}
You can then use it like this:
string fileFullPath = FindFileByName("do1.bat", #"C:\");

How to strip the full path using file info in C#

I am new to C# programming.Please suggest me how to retrieve the fullpath but using only file.Name in my code as I only want to enter file name in my listBox not full path
My code is:
listBox1.DataSource = GetFolder("..\\video\\");
private static List<string> GetFolder(string folder)
{
List<string> FileList = new List<string>();
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories)
foreach (FileInfo file in allFiles)
{
FileList.Add(file.FullName);
}
return FileList;
}
FileInfo(path).Directory.FullPath
Your actual problem of your code is missing semi-colon for this line
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories)
It should be
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories);
If I get you right, you want the FullPath as value but only the FileName displayed. To achieve this, you could use a List of FileInfos containing both of these values and tell the ListBox, which member is the value and which one should be displayed:
this.listBox1.DisplayMember = "Name";
this.listBox1.ValueMember = "FullName";
listBox1.DataSource = GetFolder("..\\video\\");
Player.URL = Convert.ToString(listBox1.SelectedValue); // Instead of SelectedItem
private static List<FileInfo> GetFolder(string folder)
{
List<FileInfo> fileList = new List<FileInfo>();
foreach (FileInfo file in new DirectoryInfo(folder).GetFiles("*.mpg", SearchOption.AllDirectories))
{
fileList.Add(file);
}
return fileList;
}
FileList.Add(file.FullName);
Please Change this line like below
FileList.Add(file.Name );
listBox1.DataSource = GetFolder("..\\video\\");
private static List<string> GetFolder(string folder)
{
List<string> FileList = new List<string>();
var allFiles = new DirectoryInfo(folder).GetFiles("*.mpg",
SearchOption.AllDirectories)
foreach (FileInfo file in allFiles)
{
FileList.Add(file.Name);
}
return FileList;
}

c# recursion folders and files directory

I am trying to retrieve all the files in all the folders I have in a directory .
But the result is quite random ..
I think the foreach is wrong ..
What I don't understand is why ?
Because in all the folders , we check all the files and then display a link buttons of all the files . But actually it's displaying a lot of folders , twice .
var DI = new DirectoryInfo("C://inetpub//wwwroot//ClientPortal//Files//")
.GetDirectories("*.*", System.IO.SearchOption.AllDirectories);
foreach (System.IO.DirectoryInfo D1 in DI)
{
System.IO.FileInfo[] fiArr = D1.GetFiles();
foreach (System.IO.FileInfo file in fiArr)
{
LinkButton lktest = new LinkButton();
lktest.Text = D1.Name;
form1.Controls.Add(lktest);
form1.Controls.Add(new LiteralControl("<br>"));
}
}
Can someone help me ?
Thanks a lot !
display a link buttons of all the files
Here you're creating link buttons with the name set to the directory when it sounds like you want the file instead (ie file.Name instead of D1.Name)
lktest.Text = D1.Name;
Does this help?
http://www.dreamincode.net/code/snippet1669.htm
public void GetDirStructure(string path)
{
try
{
DirectoryInfo dir = new DirectoryInfo(path);
DirectoryInfo[] subDirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles();
foreach(FileInfo fi in files)
{
Console.WriteLine(fi.FullName.ToString());
}
if (subDirs != null)
{
foreach (DirectoryInfo sd in subDirs)
{
GetDirStructure(path + #"\\" + sd.Name);
}
}
}
catch(Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
The first line of code seems like the culprit:
System.IO.DirectoryInfo[] DI = new System.IO.DirectoryInfo("C://inetpub//wwwroot//ClientPortal//Files//").GetDirectories("*.*", System.IO.SearchOption.AllDirectories);
Try using the following:
DirectoryInfo[] DI = new DirectoryInfo("C://inetpub//wwwroot//ClientPortal//File//").GetDirectories();

Exact file extension match with GetFiles()?

I'd like to retrieve a list of files whose extensions match a specified string exactly.
DirectoryInfo di = new DirectoryInfo(someValidPath);
List<FileInfo> myFiles = new List<FileInfo>();
foreach (FileInfo fi in di.GetFiles("*.txt"))
{
myFiles.Add(fi);
}
I get the files with extension *.txt but I also get files with the extension *.txtx, so what I've coded amounts to getting the files whose extension starts with txt.
This isn't what I want. Do I need to grab all of the filenames and do a regular expression match to "\\.txt$" (I think), or test each filename string with .EndsWith(".txt"), etc., to accomplish this?
Thanks!
Somewhat of a workaround, but you can filter out exact matches with the Where extesion method:
foreach (FileInfo fi in di.GetFiles("*.txt")
.Where(fi => string.Compare(".txt", fi.Extension, StringComparison.OrdinalIgnoreCase) == 0))
{
myFiles.Add(fi);
}
Note that this will make a case insensitive matching of the extension.
Using the AddRange feature of lists instead of doing the foreach loop and calling Add for each item returned by the expression below (which I save into the variable list).
var list = di.GetFiles("*.txt").Where(f => f.Extension == ".txt");
myFiles.AddRange(list);
I'm presuming you were just showing us a snippet of your code and myFiles already had values in it, if not, you could do instead.
List<FileInfo> myFiles = di.GetFiles("*.txt").Where(f => f.Extension == ".txt").ToList();
Regex might be overkill. Use the extension on FileInfo.
foreach (FileInfo fi in di.GetFiles("*.txt").Where(f => f.Extension == ".txt"))
{
myFiles.Add(fi);
}
Try this:
DirectoryInfo di = new DirectoryInfo(someValidPath);
List<FileInfo> myFiles =
(
from file in di.GetFiles("*.txt")
where file.Extension == ".txt"
select file
).ToList();
DirectoryInfo di = new DirectoryInfo(someValidPath);
List<FileInfo> myFiles = new List<FileInfo>();
foreach (FileInfo fi in di.GetFiles("*.txt"))
{
if (fi.Extension == ".txt")
myFiles.Add(fi);
}
Couldn't you just add an if and check the last four characters of the filename?
If you are using C# 2.0
Isn't easier ?
string fileExtensionFilter = "*.txt";
DirectoryInfo di = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
List<FileInfo> myFiles = new List<FileInfo>();
foreach (FileInfo fi in di.GetFiles(fileExtensionFilter))
{
if (fi.Extension == fileExtensionFilter.Substring(1)) myFiles.Add(fi);
}
I had a user-supplied pattern so many of the other answers didn't suit me. I ended up with this more general purpose solution:
public string[] GetFiles(string path, string pattern)
{
bool lastWildIsHook = false;
if(pattern.EndsWith("?"))
{
pattern = pattern.Substring(0, pattern.Length - 1);
lastWildIsHook = true;
}
var lastWildIndex = Math.Max(pattern.LastIndexOf("*"), pattern.LastIndexOf("?"));
var endsWith = pattern.Length > lastWildIndex ? pattern.Substring(lastWildIndex + 1) : pattern;
if(!lastWildIsHook)
return Directory.GetFiles(path, pattern).Where(p => p.EndsWith(endsWith)).ToArray();
else
return Directory.GetFiles(path, pattern).Where(p => p.EndsWith(endsWith) || p.Substring(0, p.Length - 1).EndsWith(endsWith)).ToArray();
}

Categories

Resources