How to get all the files inside a folder? - c#

In my program I have a treeview and a folderbrowser and a datagridview. The user uses the folder browser to choose a folder which contains bunch of shows which all have different seasons. My program displays the folders for the shows and the season folders inside them in the treeview and each time the select a folder from treeview I want it to display all the files inside that folder. I am currectly using this code:
public void fileProcessDirectory(string targetDirectory, string Name)
{
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
{
FileProcessFile(fileName);
}
string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
{
fileProcessDirectory(subdirectory, Name);
break;
}
}
public void FileProcessFile(string path)
{
dataGridView.Rows.Add(path, "New");
}
it shows the files inside the first sub folder that I have. it used to show all the files inside all the folders so I added a break and now it shows the first 3 files and stops there. So I want it to display the files inside the selected subfolder not all the sub folders.

You can try to modify your function as this:
public void FileProcessDirectory(string targetDirectory, string subfolder)
{
// this adds files
foreach (string fileName in Directory.GetFiles(targetDirectory))
{
FileProcessFile(fileName);
}
// if we pass subfolder as empty then nothing happens
if(string.IsNullOrEmpty(subfolder)) return;
// here we find our subfolder and display files for it
FileProcessDirectory(Directory.GetDirectories(targetDirectory).Where(d => d == targetDirectory + "\\" + subfolder).ToArray()[0], null);
}
And the ussage example:
FileProcessDirectory(Directory.GetParent(Directory.GetCurrentDirectory()).FullName, "Debug");

Please correct my understanding if I'm wrong:
user select the folder, then on treeview select the season then they should see in the data grid view all the files inside, correct ?
I implemented in this way
treeView1.NodeMouseDoubleClick += new TreeNodeMouseClickEventHandler(treeView1_NodeMouseClick);
if user double click on the treenode it shows all the files inside in the data grid:
void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (treeView1.SelectedNode != null)
{
dataGridView1.Rows.Clear();
string[] fileEntries = System.IO.Directory.GetFiles(treeView1.SelectedNode.Text);
foreach (string fileName in fileEntries)
{
dataGridView1.Rows.Add(Path.GetFileName(fileName));
}
}
}
I guess the problem before maybe caused by the dataGrid not clearing the old files. Hope it helps.

Related

Path.Combine() C#

So on my previous question (C# Only File NAMES in ListBox) I asked how to show only the file names.I got that to work. Then I encountered another problem: I could not load whats in the directory because there is no way to. A user told me
"
You either need to use a Dictionary datasource for your ListBox (with the key being the file name and the value being that path) See this answer for an idea of what I mean. Or you need to rebuild the path in your
IndexChange function (using Path.Combine() )
"
And me being me, I had no clue what he meant. So I came back for more help. I have not put any code as I don't know how to.
https://msdn.microsoft.com/it-it/library/fyy7a5kt(v=vs.110).aspx
string folder = #"C:/Aatrox";
private void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var fileName = (string)ListBox1.SelectedItem;
textEditorControl1.Text = File.ReadAllText(Paht.Combine(folder, fileName));
}
private void FlatButton3_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string[] txtfiles = Directory.GetFiles(folder, "*.txt");
string[] luafiles = Directory.GetFiles(folder, "*.lua");
foreach (var item in txtfiles)
{
ListBox1.Items.Add(Path.GetFileName(item));
}
foreach (var item in luafiles)
{
ListBox1.Items.Add(Path.GetFileName(item));
}
}
If I understand correctly, you want a List of file names from a certain directory. You want to use Directory.EnumerateFiles to get each file in the directory. Path.Combine only combines a directories path, for modularity and use on other PC's mainly, such as Path.Combine(Environment.CurrentDirectory, "Hello").

C# Move files inside dialog's path

I'm struggling with this basic operation.It will be nice if someone can write a working code.So let's say I got folder "AB" on desktop.Folder AB contains subfolder A and subfolder B.Subfolder A contains A.txt and Subfolder B contains B.txt.I want the user to simply choose folder AB via a browser dialog(I did that already) and then,when he clicks on a checkbox,file A.txt will go on subfolder B and B.txt will go on subfolder A.
I will do this for simple folders A and B. You will have to consider the chances of sub-folders as well.
string[] filesA = System.IO.Directory.GetFiles(AsourcePath);
string[] filesB = System.IO.Directory.GetFiles(BsourcePath);
foreach (string s in filesA)
{
System.IO.File.Move(s, AsourcePath);
}
foreach (string s in filesB)
{
System.IO.File.Move(s, BsourcePath);
}
Please Note: You will have consider so many scenarios for this including sub-folders, overwriting, existing files or folders etc.
Assuming that you have the folder path for both A and B folders,
var Afolder = #"D:\AB\A";
var Bfolder = #"D:\AB\B";
SwapFolderFiles(Afolder, Bfolder);
Pass the folder path for both A and B to SwapFolderFiles,
private static void SwapFolderFiles(string AFolder, string BFolder)
{
var AFolderfiles = System.IO.Directory.GetFiles(AFolder);
var BFolderfiles = System.IO.Directory.GetFiles(BFolder);
MoveFiles(AFolder, BFolder, AFolderfiles);
MoveFiles(BFolder, AFolder, BFolderfiles);
}
private static void MoveFiles(string sourceFolder, string destinationFolder, string[] folderfiles)
{
foreach (var file in folderfiles)
{
var filename = file.Substring(file.LastIndexOf("\\")+1);
var source = System.IO.Path.Combine(sourceFolder, filename);
var destination = System.IO.Path.Combine(destinationFolder, filename);
System.IO.File.Move(source, destination);
}
}

deleting contains of folder NOT the folder It self? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
DirectoryInfo.Delete vs Directory.Delete
I made this code to empty some files that I regularly delete, such as temp and MSN cahes files in Windows.
code1
I can add new paths to apply DeleteContains method in easy way I just have to add the path to the list
code2
will not allow me to add paths as much I want and I have to create new array of string for each path and a new loop too
anyway to use code1 to delete contains of the folder NOT the folder and its contains??
any work around in the foreach in code1 to work as code2 ??
Because some Folder can be delete or deleting them will cause problem for some apps and the apps wont work again it like
"C:\Users\user\AppData\Local\Temp"
while other folder can be delete it with no problem like MSN cashes
"C:\Users\user\AppData\Local\Microsoft\Windows Live\Contacts"
code1
private void Clear_Click(object sender, EventArgs e)
{
List<DirectoryInfo> FolderToClear = new List<DirectoryInfo>();
// here is a list of files I want to delete
FolderToClear.Add(new DirectoryInfo("path1"));
FolderToClear.Add(new DirectoryInfo("path2"));
FolderToClear.Add(new DirectoryInfo("path3"));
FolderToClear.Add(new DirectoryInfo("path4"));
foreach (DirectoryInfo directory in FolderToClear)
{
directory.Delete(true);
}
}
code2
private void DeleteContents(string Path)
{
string[] DirectoryList = Directory.GetDirectories(Path1);
string[] FileList = Directory.GetFiles(Path1);
foreach (string xin FileList)
{
File.Delete(x);
}
foreach ( string x in DirectoryList)
{
Directory.Delete(x, true);
}
}
Try:
DirectoryInfo directory = new DirectoryInfo("Path");
foreach (FileInfo fi in directory.GetFiles())
{
fi.Delete();
}
Better yet, here is a recursive that will delete all the files and sub directories under the DirectoryInfo you provide.
Note: There is nothing in here to handle file locks so it will bomb if you have th file open. This should get you started.
public void KeepTheseFolders(DirectoryInfo dirInfo)
{
DeleteFolder(new DirectoryInfo("Path1"), false);
DeleteFolder(new DirectoryInfo("Path2"), false);
DeleteFolder(new DirectoryInfo("Path3"), false);
DeleteFolder(new DirectoryInfo("Path4"), false);
}
public void DeleteFolder(DirectoryInfo dirInfo, bool deleteDirectory)
{
//Check for sub Directories
foreach (DirectoryInfo di in dirInfo.GetDirectories())
{
//Call itself to delete the sub directory
DeleteFolder(di, true);
}
//Delete Files in Directory
foreach (FileInfo fi in dirInfo.GetFiles())
{
fi.Delete();
}
//Finally Delete Empty Directory if optioned
if (deleteDirectory)
{
dirInfo.Delete();
}
}
Added it so you can keep your original folder

Delete Folder if it is Empty using C#

I am writing a tool that will allow me to go though a fairly large list of Directories and Sub-directories. I would like it to delete a folder if there it is empty. I can delete folders and sub folders that are empty with this code:
string dir = textBox1.Text;
string[] folders = System.IO.Directory.GetDirectories(dir, "*.*", System.IO.SearchOption.AllDirectories);
foreach (var directory in folders)
{
if (System.IO.Directory.GetFiles(directory).Length == 0 && System.IO.Directory.GetDirectories(directory).Length == 0)
{
System.IO.StreamWriter Dfile = new System.IO.StreamWriter(newpath, true);
System.IO.Directory.Delete(directory);
}
}
My question is how to have the code go though and check the folders after each delete because once it deletes a folder it could make the parent folder empty and should then should be deleted. Once the code does not find any folders or sub-folders that are empty it would exit.
Write a depth-first recursive function. As you complete each recursive call, check the current folder to see if it is empty. If it is, then delete it.
Something like this (pseudocode)
DeleteEmptyFolders(path)
{
foreach Folder f in Path
{
DeleteEmptyFolders(f);
if (f is empty)
{
Delete(f);
}
}
}
You can do this recursively like this (not tested):
void DeleteFolder(string folder) {
string[] folders = System.IO.Directory.GetDirectories(folder, "*.*", System.IO.SearchOption.AllDirectories);
foreach (var directory in folders)
{
DeleteFolder(directory);
}
//delete this folder if empty
}
Here's an idea (this isn't tested)
while ( true )
{
DirectoryInfo parent = Directory.GetParent(current.FullName);
if ( parent.GetFiles().Length == 0 && parent.GetDirectories().Length == 0 )
{
current = parent;
current.Delete();
}
else
{
break;
}
}
This walks up the tree of the current directory to delete any parent directories that are empty.
By the look of it your are trying to delete any folder which does not contain a file. I believe this would do the trick for you. I tested it with a small folder set that went 5 levels deep and a single file in a couple of locations. All folders which did not have files were deleted. All files were left intact. Small tweak to a snippet found... Thanks Matt Smith.
Cannot delete directory with Directory.Delete(path, true)
string[] dirs = System.IO.Directory.GetDirectories(Directory.GetCurrentDirectory(), "*.*",SearchOption.AllDirectories);
foreach (string d in dirs)
{
if (System.IO.Directory.Exists(d)) {
if (System.IO.Directory.GetFiles(d, "*.*", SearchOption.AllDirectories).Length == 0)
{
DeleteDirectory(d);
}
}
}
public static void DeleteDirectory(string target_dir)
{
string[] dirs = Directory.GetDirectories(target_dir);
foreach (string dir in dirs)
{
DeleteDirectory(dir);
}
Directory.Delete(target_dir, false);
}
this will delete all empty (sub)folders in a given directory
https://stackoverflow.com/a/16688997/2408998

how to read all the subdirectories in a given destination which contain Master File in it

I am having a problem .
My Problem is to read all the subdirectories in a given destination which contain Master file .
I can read subdirectories but i am creating a project which only read given directory which should contain Master file in the directory .
In the given directory a file called Master file should be there.
I want to write the code like if the given directory doesnot contain any Master file in it it should Jump to another Directory.
My source Directory is #"C:\test.
In #"C:\test" there are many folders and subfolders .
the test directory contains "C:\test\test1\test2\test3 . In this path test3 folder contains Master file test1 and test2 doesn't .
I want to write this code something like this,
MLMReader Reader = new MLMReader();
Reader.OpenDirectory(#"C:\test");
if (!File.Exists(test + "\\Master"))
{
//i want to loop the "C"\\" and if test1 does not contain
// Master File then jump to another directory test2, if
//test2 directory contain Master File then the work should
// continue after finishing go to test3
}
Is there any way to do .
Any suggestions for my problem.
I haven't tested, but I'm pretty sure the following will work:
string[] paths = Directory.GetFiles(dirPath, "MasterFile", SearchOption.AllDirectories);
Then you can just foreach over the resulting array, if you want to go through all MasterFiles. Or if you just care about the first result, then it's just paths[0] -- of course, means it does a lil bit extra work finding all matching paths. And you probably don't need a check for an empty array as an index out of bounds would indicate there's no MasterFile (unless you want to catch that and then rethrow as file not found exception or whatever).
Linq-to-FileSystem allows you to perform structured queries on your file system. See the following example:
var dir = new DirectoryInfo(#"C:\test");
// find all subdirectories of test that contains a file / folder called 'Master'
var dirs = dir.Elements()
.Where(d => d.Elements().Any(i => i.Name == "Master"))
this is my code where I program with directorys, hope it will help you.
using System;
using System.IO;
static void Print(string path, int? rec, int? tree, bool color, int? level = 0)
{
if ((rec != null && level > rec) || path == null) return;
if (rec == null) rec = 0;
string[] dir;
string[] fil;
try
{
dir = Directory.GetDirectories(path);
fil = Directory.GetFiles(path);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
return;
}
foreach (string s in dir)
{
WriteSpace(level,tree);
Console.WriteLine(s);
Print(s, rec, tree, color, level + 1);
}
if (color)
{
ConsoleColor def = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Blue;
foreach (string s in fil) // vypis file
{
WriteSpace(level, tree);
Console.WriteLine(s);
}
Console.ForegroundColor = def;
}
else
{
foreach (string s in fil)
{
WriteSpace(level, tree);
Console.WriteLine(s);
}
}
}
private static void WriteSpace(int? level, int? tree)
{
for (int i = 0; i < level*tree; i++)
Console.Write(" ");
}
}
Here's a Recursive Example on how you can traverse a directory structure and look for a certain file, once it is found you can call the corresponding method.
static void Main()
{
TraverseDirectory(#"D:\TestDirectory");
}
static void DoSomethingWithMaster(string path)
{
Console.WriteLine("Found master at {0}", path);
}
static void TraverseDirectory(string directory)
{
var currentDirectory = new DirectoryInfo(directory);
foreach(var dir in currentDirectory.GetDirectories())
{
var currentPath = dir.FullName;
TraverseDirectory(currentPath);
var pathToMasterFile = Path.Combine(currentPath, "Master");
if (File.Exists(pathToMasterFile))
DoSomethingWithMaster(pathToMasterFile);
}
}
I have the following Folder Structure:
D:\TestDirectory\1
D:\TestDirectory\2
D:\TestDirectory\3
D:\TestDirectory\4
D:\TestDirectory\4\Master
D:\TestDirectory\5
And when running the above it prints: Found master at D:\TestDirectory\4
All you need for this is:
using System;
using System.IO;
You can also move TraverseDirectory(currentPath); to the end of the foreach-loop, where you put it depends on when you want to detect the file, do you want to go deep and then climb your way back and check for the Master-file on the way up, or do you want to check for the master file before you enter the next directory?
According to your question, you might want to swap them in my answer and if I understand you correctly, you might not even want to go to the next directory after finding one master-file?
foreach(var dir in currentDirectory.GetDirectories())
{
var currentPath = dir.FullName;
var pathToMasterFile = Path.Combine(currentPath, "Master");
if (File.Exists(pathToMasterFile))
DoSomethingWithMaster(pathToMasterFile);
TraverseDirectory(currentPath);
}
In this example, it does exactly what you are saying in your commented code inside your if. It will first check TestDirectory\1 for a Master file and then go further down the line. If you don't care about any other Master-files in one sub-directory once it is found, you can just nest TraverseDirectory(pathToMasterFile) inside an else-block.
Edit
You might want to use EnumerateDirectories, see MSDN for details.

Categories

Resources