Finding files in specific folder in different directories - c#

I need to find a lot of files (images) in a specific folder (for exemple CR7), in different directories.
Imagine I have a network share that I have to find and display all images in that specific folder (CR7). CR7 folder can be found in different places like:
\\share\folder01\CR7 or: \\share\folder01\folder02\CR7 or anything else.
What I have is this, but results from filesList dont go to datagridview:
public partial class FormProcuraFotos : Form
{
DataTable tableWithPhotos;
public FormProcuraFotos()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Visible = true;
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += this.Worker_DoWork;
worker.RunWorkerCompleted += this.Worker_RunWorkerCompleted;
worker.RunWorkerAsync();
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
// Create the new DataTable to be used
tableWithPhotos = new DataTable();
tableWithPhotos.Columns.Add("Filenames");
tableWithPhotos.Columns.Add("Ctrl+C");
//Find files on a specific folder (CR7)
string allDir = #"\\server\folder01";
var CR7Directories = Directory.EnumerateDirectories(allDir, "CR7", SearchOption.AllDirectories);
List<string> extensions = new List<string>() { ".jpg", ".bmp", ".png", ".tiff", ".gif" };
List<string> filesList = new List<string>();
foreach (var dir in CR7Directories)
{
List<string> FileNames = new DirectoryInfo(dir).EnumerateFiles(dir)
.Where(x => extensions.Contains(x.Extension))
.Select(x => x.Name).ToList();
filesList.AddRange(FileNames);
}
// And now here we will add all the files that it has found into the DataTable
foreach (string entryFiles in filesList)
{
DataRow row = tableWithPhotos.NewRow();
row[0] = Path.GetFileName(entryFiles);
row[1] = entryFiles;
tableWithPhotos.Rows.Add(row);
}
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Visible = false;
var formToOpen = new FormResultadosFotos(tableWithPhotos);
formToOpen.Show();
}
}

I think you have to split the execution by following steps:
Get all Directories with name "CR7" under the specified folder by specifying "CR7" as searchPattern.
Now you have all CR7 folder paths, Iterate through those collection and Get List of files and filter them based on the extension list, in each CR7 directory.
Can you please try this and let me know whether it solved your issues:
string allDir = #"\\share\folder01";
var CR7Directories = Directory.EnumerateDirectories(allDir, "CR7", SearchOption.AllDirectories);
List<string> extensions = new List<string>() { ".jpg", ".bmp", ".png", ".tiff", ".gif" };
List<string> filesList = new List<string>();
foreach (var dir in CR7Directories)
{
List<string> FileNames = new DirectoryInfo(dir).EnumerateFiles(dir)
.Where(x => extensions.Contains(x.Extension))
.Select(x => x.Name).ToList();
filesList.AddRange(FileNames);
}

Related

webBrowser control not displaying PDF

I have problem in displaying pdf image in the webBrowser control. The file name is search in the web browser.
refer to image below:
Code:
FolderBrowserDialog FBD = new FolderBrowserDialog();
if (FBD.ShowDialog() == DialogResult.OK)
{
//textBox5.Text = new DirectoryInfo(FBD.SelectedPath).Parent.Parent.Name;
string[] files = Directory.GetFiles(FBD.SelectedPath, "*.pdf");
// string[] dirs = Directory.GetDirectories(FBD.SelectedPath);
foreach (string file in files)
{
listBox1.Items.Add(new FileInfo(file).Name);
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string filedirectory = listBox1.SelectedItem.ToString();
// if (listBox1.SelectedItem != null && listBox1.SelectedItem is string)
{
webBrowser1.Navigate(filedirectory);
// if (this.listBox1.SelectedIndex >= 0)
Instead of this:
string[] files = Directory.GetFiles(FBD.SelectedPath, "*.pdf");
foreach (string file in files)
{
listBox1.Items.Add(new FileInfo(file).Name);
}
do this:
var folder = new DirectoryInfo(FBD.SelectedPath);
var files = folder.GetFiles("*.pdf");
listBox1.DisplayMember = nameOf(FileInfo.Name);
listBox1.ValueMember = nameOf(FileInfo.FullName);
listBox1.DataSource = files;
and then, instead of this:
string filedirectory = listBox1.SelectedItem.ToString();
do this:
var filePath = (string)listBox1.SelectedValue;
Note the use of a variable name that actually describes what the variable represents. "filedirectory" is a nonsense.

Add results do datagridview

I am trying to make an app that finds all images on a specific folder (exemple: CR7) and not on all directories. I have a network share and a lot of directories where I can find that specific folder "CR7". I only need images from that CR7 folder. I cand find them and trying to put those results on a datadridview, but without success. Any ideas why filesList does not go to datatable?
Here is the code:
{
public partial class FormProcuraFotos : Form
{
DataTable tableWithPhotos;
public FormProcuraFotos()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Visible = true;
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += this.Worker_DoWork;
worker.RunWorkerCompleted += this.Worker_RunWorkerCompleted;
worker.RunWorkerAsync();
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
// Create the new DataTable to be used
tableWithPhotos = new DataTable();
//Find files on a specific folder (CR7)
string allDir = #"\\share\folder01";
var CR7Directories = Directory.EnumerateDirectories(allDir, "CR7", SearchOption.AllDirectories);
List<string> extensions = new List<string>() { ".jpg", ".bmp", ".png", ".tiff", ".gif" };
List<string> filesList = new List<string>();
foreach (var dir in CR7Directories)
{
List<string> FileNames = new DirectoryInfo(dir).EnumerateFiles(dir)
.Where(x => extensions.Contains(x.Extension))
.Select(x => x.Name).ToList();
filesList.AddRange(FileNames);
}
// And now here we will add all the files that it has found into the DataTable
foreach (string entryFiles in filesList)
{
DataRow row = tableWithPhotos.NewRow();
row[0] = Path.GetFileName(entryFiles);
row[1] = entryFiles;
tableWithPhotos.Rows.Add(Path.GetFileName(entryFiles), entryFiles);
}
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Visible = false;
var formToOpen = new FormResultadosFotos(tableWithPhotos);
formToOpen.Show();
}
}
}
I think you are adding new row to datagridview like a datatable and it doen's work.
With datagridview, you can do:
tableWithPhotos.Rows.Add(Path.GetFileName(entryFiles), entryFiles);
Or [If there is any row in your datagridview], you can do:
DataGridViewRow row = (DataGridViewRow)tableWithPhotos.Rows[0].Clone();
row[0] = Path.GetFileName(entryFiles);
row[1] = entryFiles;
tableWithPhotos.Rows.Add(row);
Please refer this link for more details: DataGridViewRows
Because you are creating new form and add a datagrid to it, then the result is null. You can do as bellow:
option1: make filesList as a member of the class, and create new form base on filesList instead of the DataGridView tableWithPhotos, and add row to DataGridView in FormResultadosFotos similar with common your current code.
var formToOpen = new FormResultadosFotos(filesList);
formToOpen.Show();
option 2: modify your constructor of FormResultadosFotos:
public FormResultadosFotos(DataGridView dataGridView)
{
InitializeComponent();
dataGridView1.Rows.Clear();
foreach (DataGridViewRow row in dataGridView.Rows)
{
dataGridView1.Rows.Add(row.Cells[0].Value, row.Cells[1].Value);
}
}
P/S: Make sure that your DataGridView in your FormResultadosFotos already had 2 columns.
Cheer!

Get files in directory with multiple search patterns

I have a method that gets files in specified directory with extension txt. Besides those files, I want to also get files with extensions ppt, docx etc. How to achieve that?
this is my current code:
private void button2_Click(object sender, EventArgs e){
listView1.Items.Clear();
if (textBox1.Text != ""){
List<string> files = new List<string>();
files = Directory.GetFiles(textBox1.Text, "*.txt,*.ppt").ToList();
progressBar1.Maximum = files.Count;
progressBar1.Value = 0;
ListViewItem it;
foreach (var file in files){
it = new ListViewItem(file.ToString());
it.SubItems.Add(System.IO.Path.GetFileName(file.ToString()));
it.SubItems.Add(System.IO.Path.GetExtension(file.ToString()));
listView1.Items.Add(it);
progressBar1.Increment(1);
}
} else
MessageBox.Show("Select directory first");
}
Your question is not clear but which i understand you want to get files with different extension from a specified path. We can't do this using Directory.GetFiles("c://etc.", "*.txt") because it works on a single search pattern. You can use this,
string[] Extensions = {"*.txt", "*.doc", "*.ppt"};
foreach(var ext in Extensions)
{
GetFiles(ext);
}
private void GetFiles(string ext)
{
List<string> files = new List<string>();
files = Directory.GetFiles("c:/something", ext).ToList();
// Something you want to do with these files.
}
files = Directory.GetFiles(#textBox1.Text, "*.txt").ToList();
files.AddRange(Directory.GetFiles(#textBox1.Text, "*.docx").ToList());
files.AddRange(Directory.GetFiles(#textBox1.Text, "*.ppt").ToList());
also, you should consider checking for validity of path from textBox1, something like this:
if (!Directory.Exists(#textBox1.Text))
{
MessageBox.Show("invalid folder");
return;
}

Returning specific file type from sub directory

By implying this call I am getting the name of current directory.I have a list of sub-directories inside a directory.
Users\Xeon\Documents\Visual Studio2013\Projects\Consolesocket1\Consolesocket1\Data
After this call I get return value named folder which is sub folder inside it.This is one task I want to accomplish.
Now how can i retrieve files inside this selected each sub directory with specific file type
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button2_Click(object sender, EventArgs e)
{
string[] extensions = { ".xml", ".ddg" };
string[] dizi = Directory.GetFiles(textBox1.Text, "*.*", SearchOption.AllDirectories)
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
string[] dizin = Directory.GetDirectories(textBox1.Text, "P*", SearchOption.TopDirectoryOnly);
foreach (var i in dizin)
{
FileInfo f = new FileInfo(i);
listBox1.Items.Add(f.Name);
}
string[] di = Directory.GetDirectories(textBox1.Text, "S*", SearchOption.TopDirectoryOnly);
foreach (var z in di)
{
FileInfo f = new FileInfo(z);
listBox1.Items.Add(f.Name);
}
}
You did correctly by specifying the extensions, and using the
SearchOption.AllDirections.
The first dizin variable will contain all files.

How to get files more than one extension? [duplicate]

This question already has answers here:
Can you call Directory.GetFiles() with multiple filters?
(27 answers)
Closed 9 years ago.
I have a program which gives random files. It is simple but I'm quite new to this.
Im having trouble with creating fileinfo list of files. I added a contextmenustrip which has multiple choose of file genre (e.g: video files, text files..)
I wanted to define string array with cntxtmnustrp. and want it make new array and combine with previous. But it didnt work. Should I create a arraylist and add each list to this?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Random r = new Random();
string path1;
DirectoryInfo dif;
// List<FileInfo> files;
FileInfo[] files;
FileInfo[] newfiles;
int randomchoose;
int fok;
int kok, pd;
string[] filetypes;
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog hoho = new FolderBrowserDialog(); // yeni dosya yeri
hoho.ShowNewFolderButton = true;
if (hoho.ShowDialog() == DialogResult.OK)
{
path1 = hoho.SelectedPath;
textBox1.Text = path1;
dif = new DirectoryInfo(path1);
foreach (string ft in filetypes)
{
files = dif.GetFiles("*.ft", SearchOption.AllDirectories);
//files.AddRange(dif.GetFiles(string.Format("*.{0}", ft), SearchOption.AllDirectories));
newfiles = newfiles.Concat(files);
}
//pd = liste.Length;
pd = files.Length;
kok = pd;
}
}
}
private void button1_Click_1(object sender, EventArgs e)
{
listBox1.Sorted = true;
}
private void cesit_Click(object sender, EventArgs e)
{
//contextMenuStrip1.Show();
contextMenuStrip1.Show(this.PointToScreen(cesit.Location));
}
private void videoFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
filetypes = new string[2] { "txt", "png" };
}
private void musicFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
//tur = ".png";
//textBox4.Text = tur;
}
private void textFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
}
}
Assuming I understand what you mean, I'd make the files array into a List, by replacing:
FileInfo[] files;
with:
List<FileInfo> files;
That means you'd change:
files = dif.GetFiles("*.ft", SearchOption.AllDirectories);
to:
files.AddRange(dif.GetFiles(string.Format("*.{0}", ft) SearchOption.AllDirectories));
You can then get rid of the list concatenation:
newfiles = newfiles.Concat(files);

Categories