I would like to ask is there any way to get all the folder/directory name in a path:
My problem is:
I would like to get several folders in Local Disk C: but I don't want to use the following code to search all the folder in C: which causes the program stuck.
foreach (string dirPath in Directory.GetDirectories(source, "*", SearchOption.AllDirectories))
{
...
}
Try this:
using System.IO;
var directories = Directory.GetDirectories("c:\\");
This should give you all the directories at the root level of the C drive.
Try this:
string[] dirs = Directory.GetDirectories(#"c:\", "*", SearchOption.TopDirectoryOnly);
This should give you just top directory only.
Related
I have a main folder which contains many sub directories. Inside each sub directory, there are many sub directories.
Does anyone knows how can I loop through the many sub directories in each sub directory?
This is my codes currently:
if (Directory.Exists(MainDirectory))
{
foreach (DirectoryInfo SubDir in new DirectoryInfo(MainDirectory).GetDirectories())
{
foreach (FileInfo Image in SubDir.GetFiles())
{
Image.Delete();
}
SubDir.Delete(true);
}
Directory.Delete(MainDirectory, true);
}
My current codes will only loop through the images from each subdirectory from the main directory.
Please help me on this.
You can use the Directory SearchOption.AllDirectories or you can use recursive call for it, whichever is appropriate.
If what you really interested in are files rather than to enter the sub-directories themselves, the method that you can use is Directory.GetFiles, something like this:
string[] files = Directory.GetFiles(folderpath, "*", SearchOption.AllDirectories); //"*" denotes all file format
the return is string[] which contains all filepaths in the given folderpath including those which are in the sub-directories.
You can change the SearchPattern ("*" in the example) to suit the file search pattern (formats) which you need.
If you really need to enter the sub-directory however, you can create recursive calls and in the call, you can check if the directory has further (deeper) folder by using DirectoryInfo.GetDirectories()
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);
There are many .bmp files present in my C:\TEMP directory.
I am using following code to delete all .bmp file in my C:\TEMP directory but somehow its not working as I expect. Can anyone help me in this?
string[] filePaths = Directory.GetFiles(#"c:\TEMP\");
foreach (string filePath in filePaths)
{
if (filePath.Contains(".bmp"))
File.Delete(filePath);
}
I have already checked that .bmp file and the directory has no read only attribute
For starters, GetFiles has an overload which takes a search pattern http://msdn.microsoft.com/en-us/library/wz42302f.aspx so you can do:
Directory.GetFiles(#"C:\TEMP\", "*.bmp");
Edit: For the case of deleting all .bmp files in TEMP:
string[] filePaths = Directory.GetFiles(#"c:\TEMP\", "*.bmp");
foreach (string filePath in filePaths)
{
File.Delete(filePath);
}
This deletes all .bmp files in the folder but does not access subfolders.
Should also use .EndsWith instead of .Contains
You Could write below code in fast way:
string[] t = Directory.GetFiles(Environment.CurrentDirectory, "*.pdf");
Array.ForEach(t, File.Delete);
or For Text Files:
string[] t = Directory.GetFiles(Environment.CurrentDirectory, "*.txt");
Array.ForEach(t, File.Delete);
So, You could write code for all extension and all directories.
We use absolut path or relatvie path to find a file in our C# application right now. Is there a way to find the file just by its name if the file is under the currect working directory or under one of the "paths"?
Use absolute pathe is not good and use relative path is not good enough because we may change project structure by rename or move project folders. If we our code can automatically search current working directory, its subfolders and search system path, that will be more flexible.
thanks,
You can easily build a recursive function to do this for you. Look at Directory.GetDirectories and Directory.GetFiles, both under System.IO
Try this:
string target = "yourFilenameToMatch";
string current = Directory.GetCurrentDirectory();
// 1. check subtree from current directory
matches=Directory.GetFiles(current, target, SearchOption.AllDirectories);
if (matches.Length>0)
return matches[0];
// 2. check system path
string systemPath = Environment.GetEnvironmentVariable("PATH");
char[] split = new char[] {";"};
foreach (string nextDir in systemPath.Split(split))
{
if (File.Exists(nextDir + '\\' + target)
{
return nextDir;
}
}
return String.Empty;
You could call Directory.GetFiles for each root folder in which you want to search for the file. the parameter searchOption allow you to specify whether the search operation look in all subdirectories or only the directory specified. E.g:
public string GetFileName(string[] folders,string fileName) {
string[] filePaths;
foreach(var folder in folders) {
filePaths=Directory.GetFiles(folder,fileName,SearchOption.AllDirectories)
if (filePaths.Lenght>0)
return filePaths[0];
}
}
Try this:
Directory.EnumerateFiles(pathInWhichToSearch, fileNameToFind, SearchOption.AllDirectories);
And, you need to use:
using System.IO;
on top of your class.
This searches all subdirectories of pathInWhichToSearch for a file with name fileNameToFind (it can be a pattern too - like *.txt) and returns result as IEnumerable<string> with full paths of found files.
You can get the exe's directory using
Path.GetDirectoryName(Application.ExecutablePath);
Example Code: http://www.csharp-examples.net/get-application-directory/
And then, you can search the folders from there using recursion. This is a good article on recursive searching for files:
http://support.microsoft.com/kb/303974
This is a simple question and I am sure you C# Pros know it.
If you want to grab the contents of a directory on a hard drive (local or otherwise) in a C Sharp program, how do you go about it?
Call Directory.GetFiles.
If you mean get a directory then it is very simple. The following code will give you a list of all the directories in a given directory and then list all the files in the directory:
string dir = #"C:\Users\Joe\Music";
DirectoryInfo dirInfo = new DirectoryInfo(dir);
FileInfo[] files = dirInfo.GetFiles();
DirectoryInfo[] directories = dirInfo.GetDirectories();
foreach (DirectoryInfo directory in directories)
Console.WriteLine(directory.Name);
foreach (FileInfo file in files)
Console.WriteLine (file.Name);