Display only image file extensions within a Listbox - c#

Is it possible to display a listbox content, with only certain files that have a certain format? like BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff only these files with these extensions that I want to display within the lstFiles listbox.
I have tried,
lstFiles.Filter = "BMP|*.bmp|GIF|*.gif|JPG|*.jpg;*.jpeg|PNG|*.png|TIFF|*.tif;*.tiff";
But this did not work, is it possible?
EDIT:
I have three joint listboxes to display the system drive, folders and its content
private void lstDrive_SelectedIndexChanged_1(object sender, EventArgs e)
{
lstFolders.Items.Clear();
try
{
DriveInfo drive = (DriveInfo)lstDrive.SelectedItem;
foreach (DirectoryInfo dirInfo in drive.RootDirectory.GetDirectories())
lstFolders.Items.Add(dirInfo);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void lstFolders_SelectedIndexChanged_1(object sender, EventArgs e)
{
lstFiles.Items.Clear();
DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;
foreach (FileInfo fi in dir.GetFiles())
lstFiles.Items.Add(fi);
}
private void lstFiles_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBox1.Image = Image.FromFile(((FileInfo)lstFiles.SelectedItem).FullName);
}
private int lastIndex = 0;
private void lstFiles_KeyUp(object sender, KeyEventArgs e)
{
if (lstFiles.SelectedIndex == lastIndex)
{
if (e.KeyCode == Keys.Up)
{
lstFiles.SelectedIndex = lstFiles.Items.Count - 1;
}
if (e.KeyCode == Keys.Down)
{
lstFiles.SelectedIndex = 0;
}
}
lastIndex = lstFiles.SelectedIndex;
}
}
}

You are population the listbox yourself using a FileInfo object. FileInfo has a property Extension. You can use that one for filtering:
private void lstFolders_SelectedIndexChanged_1(object sender, EventArgs e)
{
lstFiles.Items.Clear();
DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;
foreach (FileInfo fi in dir.GetFiles())
switch(fi.Extension.ToUpperInvariant())
{
case ".BMP":
case ".JPG":
...
lstFiles.Items.Add(fi);
break;
}
}

Ok, I personaly have no idea nor have ever heard of using "filter" on a list box. Why don't you just add the items you want when you have the list?
lstFiles.Items.Clear();
List<string> allowedExtensions = new List<string>() {".jpg", ".png", ".gif"};
DirectoryInfo dir = (DirectoryInfo)lstFolders.SelectedItem;
foreach (FileInfo fi in dir.GetFiles().Where((x)=>allowedExtensions.Contains(x)))
{
lstFiles.Items.Add(fi);
}

Related

Drag and Drop only PDF files

I have the following code that list the files that i drag in a listbox.
now i need to filter so it can only list PDF files and discard the rest.
private void Form1_Load(object sender, EventArgs e)
{
listBoxFiles.AllowDrop = true;
listBoxFiles.DragDrop += listBoxFiles_DragDrop;
listBoxFiles.DragEnter += listBoxFiles_DragEnter;
}
private void listBoxFiles_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
private void listBoxFiles_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
listBoxFiles.Items.Add(file);
}
Try this:
private void listBoxFiles_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
if (Path.GetExtension(file) == "pdf")
{
listBoxFiles.Items.Add(file);
}
}
}
Also, if it works - you can make it in one line with Linq

Searching inside a subfolder in asp.net

How can I search a file thats inside a subfolder
Here's my code it currently searches the parent folder only it won't search inside the sub folder:
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string[] files = Directory.GetFiles(Server.MapPath("~/files"));
foreach (string item in files)
{
string fileName = Path.GetFileName(item);
if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))
{
ListBox1.Items.Add(fileName);
}
}
}
You can do it like this
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string[] files = Directory.GetFiles(Server.MapPath("~/files"), "*.*", SearchOption.AllDirectories);
foreach (string item in files)
{
string fileName = Path.GetFileName(item);
if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))
{
ListBox1.Items.Add(fileName);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
DirectoryInfo di =
new DirectoryInfo(Server.MapPath("~/files"));
FileInfo[] files =
di.GetFiles("*", SearchOption.AllDirectories);
foreach (FileInfo item in files)
{
string fileName = item.Name;
if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))
{
ListBox1.Items.Add(fileName);
}
}
}

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);

Loading large amount of text files from a share drive to search for a world. C#

Im trying to perform a search in a share drive that contains at least 90,000 files.
The code below is what I have:
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("No folder: Not listed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
List<string> allFiles = new List<string>();
AddFilesnames(sourceFolder, allFiles);
foreach (string fileName in allFiles)
{
string contents = File.ReadAllText(fileName);
if (contents.Contains(searchword))
{
listBox1.BeginUpdate();
listBox1.Items.Add(fileName);
listBox1.EndUpdate();
label4.Text = (Convert.ToInt32(label4.Text) + 1).ToString();
}
}
if (listBox1.Items.Count == 0)
{
MessageBox.Show("no files");
}
}
}
public void listboxtofile()
{
DialogResult resDialog = dlgSaveFile.ShowDialog();
if (resDialog.ToString() == "OK")
{
FileInfo fi = new FileInfo(dlgSaveFile.FileName);
StreamWriter sw = fi.CreateText();
foreach (string sItem in listBox1.Items)
{
sw.WriteLine(sItem);
}
sw.Close();
}
}
public void AddFilesnames(string sourceDir, List<string> allFiles)
{
string[] fileEntries = Directory.GetFiles(sourceDir);
foreach (string fileName in fileEntries)
{
DateTime from1 = dateTimePicker1.Value.Date;
DateTime to1 = dateTimePicker2.Value.Date;
DateTime creationTime = File.GetCreationTime(fileName);
if (creationTime >= from1 && creationTime <= to1)
{
allFiles.Add(fileName);
}
}
//Recursion
string[] subdirectoryEntries = Directory.GetDirectories(sourceDir);
foreach (string item in subdirectoryEntries)
{
// Avoid "reparse points"
if ((File.GetAttributes(item) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
{
AddFileNamesToList(item, allFiles);
label4.Text = (Convert.ToInt32(label4.Text) + 1).ToString();
}
}
}
private void button3_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
textBox1.Clear();
}
private void button5_Click(object sender, EventArgs e)
{
listboxtofile();
}
}
}
So far this is working with 3,000 files but I need to have access to a shared drive that contains 90,000 files and when I try to search in the share drive the windows form get frozen. I will really apreciate any help from you all.
My suggestion would be to do any file system work in a separate thread. If you do the file searching in the same thread as your form, Windows has no chance to update the form. You won't be able to update any of your form controls (like listBox1) directly from the new thread, but you can look into delegates and C# threading in general for ways to work around this.
Also, if you just need to search files for a specific word, have you looked into existing tools like grep?

Show selected text file from one listbox in another

This is my code:
protected void Button1_Click(object sender, EventArgs e)
{
FileInfo SelectedFileInfo = (FileInfo)ListBox1.SelectedItem;
StreamReader FileRead = new StreamReader(SelectedFileInfo.FullName);
string CurrentLine = "";
//int LineCount = 0;
while(FileRead.Peek() != -1)
{
CurrentLine = FileRead.ReadLine();
//LineCount++;
//if(LineCount % 5 == 2)
{
ListBox2.Items.Add(CurrentLine);
}
}
FileRead.Close();
}
but throws exception about:
Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'System.IO.FileInfo'
When populating the listbox, use the filename instead instead the FileInfo
Then when in Button1_Click, use ListBox1.SelectedValue to get the selected file name
protected void Button1_Click(object sender, EventArgs e)
{
ListBox2.Items.Clear();
if (ListBox1.SelectedIndex > -1)
{
string filename = ListBox1.SelectedValue;
StreamReader FileRead = new StreamReader(filename);
string CurrentLine = "";
//int LineCount = 0;
while (FileRead.Peek() != -1)
{
CurrentLine = FileRead.ReadLine();
ListBox2.Items.Add(CurrentLine);
}
FileRead.Close();
}
else
{
ListBox2.Items.Add("Please select a file first");
}
}
protected void Btn_Load_Click(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\errorlog");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
ListBox1.Items.Add(file.FullName);
}
}
}

Categories