How to search contain in name File C# - c#

I want to search for the characters in Name file of the Directory. If the content is different from the results found, delete the file. I've tried the code below:
private void btnStart_Click(object sender, EventArgs e)
{
FileWithFilter(Parth, "Abc123");
}
private void FileWithFilter(string folderName, string filesToExclude)
{
DateTime dateTime = DateTime.Now;
DirectoryInfo dir = new DirectoryInfo(folderName);
foreach (FileInfo fi in dir.GetFiles())
{
if (!fi.Name.Contains(filesToExclude))
{
fi.delete();
}
}
}
It works, but if the file in Directory is more than 10 or 11(file), code can't run correctly!
please tell me any better way or other solution.

I would propose to save all files which should be deleted in a list and then delete them afterwards. It is not recommendd to manipulate the list you are iterating over.
private void FileWithFilter(string folderName, string filesToExclude)
{
List<string> filesToBeDeleted = Directory.GetFiles(folderName).Where(m => !m.Contains(filesToExclude)).ToList();
filesToBeDeleted.ForEach(m => File.Delete(m));
}

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").

How to get all the files inside a folder?

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.

Crawling a directory

I have this test path:
private static string dCrawler = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "TestLetters";
Is there a way to say:
foreach (item in dCrawler)
{
if (item.isFile)
{
// check file info date modified code
} else
{
foreach (fileinfo file in ...
}
}
so far I have only found ways to check a file in a directory. Is the only way to do it by having two separate loops one for files and one for folders?
You can use Directory.GetFiles(); that returns a string[] and use the string value to create your FileInfo. Like this
foreach (string n in Directory.GetFiles(dCrawler))
{
FileInfo b = new FileInfo(n);
}
To get directories, you can similarly use Directory.GetDirectories();
foreach (string n in Directory.GetDirectories(dCrawler))
{
DirectoryInfo b = new DirectoryInfo(n);
}

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

Scanning Computer and displaying files in listbox?

Ok, i have some code that will scan my computer and find .txt files and display them in a listbox:
private void button2_Click(object sender, EventArgs e)
{
IEnumerable<string> files = System.IO.Directory.EnumerateFiles(#"C:\", "*.txt*", System.IO.SearchOption.AllDirectories);
foreach (var f in files)
{
listBox1.Items.Add(String.Format("{0}", f));
}
}
I get an error every time i run this. It says i do not authorization to the trash bin. I do not care weather it scans the trash or not. It there any way to exclude the trash bin out of the scan? Also, can someone help me improve my code, if you see anything wrong! Thanks!
Quickest way is to put them under a try-catch block because EnumerateFiles function does not have access to the restricted files because of the operating system permissions.
private void SearchDrives()
{
foreach (String drive in Directory.GetLogicalDrives())
{
try
{
// Search for folders into the drive.
SearchFolders(drive);
}
catch (Exception) { }
}
}
//---------------------------------------------------------------------------
private void SearchFolders(String prmPath)
{
try
{
foreach (String folder in Directory.GetDirectories(prmPath))
{
// Recursive call for each subdirectory.
SearchFolders(folder);
// Create the list of files.
SearchFiles(folder);
}
}
catch (Exception) { }
}
//---------------------------------------------------------------------------
private void SearchFiles(String prmPath)
{
try
{
foreach (String file in Directory.GetFiles(prmPath))
{
FileInfo info = new FileInfo(file);
if (info.Extension == ".txt")
{
listBox1.Items.Add(info.Name);
}
}
}
catch (Exception) { }
}
//---------------------------------------------------------------------------
Not just the recycle bin, it will also fail to read the file header of several files into your system direcotry.
In general you can do it so that you do recursive calls for every folder and just use try/catch blocks to see witch ones you can or can't access. But as Andras suggested I would also go with what allready exists will save you time
Another aproach on your example

Categories

Resources