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);
}
}
}
Related
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
I have this code that populates my listbox that contains what I type in the textbox. My problem is how can I view the selected item in my listbox in a image viewer since all my files are images? Am I missing something?
Here's my code:
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string[] files = Directory.GetFiles(Server.MapPath("~/images"), "*.*", 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 ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DocumentImage.ImageUrl = Directory.GetDirectories("~/images") + ListBox1.SelectedItem.ToString();
}
This should work I think:
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
string[] files = Directory.GetFiles(Server.MapPath("~/images"), "*.*", SearchOption.AllDirectories);
foreach (string item in files)
{
string fileName = Path.GetFileName(item);
if (fileName.ToLower().Contains(TextBox1.Text.ToLower()))
{
string subPath = item.Substring(Server.MapPath("~/images").Length).Replace("\\","/");
ListBox1.Items.Add(new ListItem(fileName, subPath));
}
}
}
In this part, you need to not only have the file name, but also the path where the file was found. In my sample, the sub path where the file was found is first set into subPath and that is then stored as the value for the list item.
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DocumentImage.ImageUrl = "~/images" + ListBox1.SelectedItem.Value;
}
Here we use the sub path to set the correct url to the image.
Note that you need to have the AutoPostBack set to true on the DocumentImage in your asxp page in order for the image to change when you change the selection in the list box.
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);
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);
}
This lists all files in all directory's from the directory i choose with folderBrowserDialog1, but when it loads them into the listBox it comes up with the item in the listBox like this
C:\users\username\desktop\filename.exe
C:\users\username\desktop\filename.exe
C:\users\username\desktop\filename.exe
and so on.. is there any way to remove C:\users\username\desktop\ and just keep filename.exe
Here's my code it may help.
private void DirSearch(string dir)
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
foreach (var file in files)
{
ListBox2.Items.Add(file);
}
}
Use Path.GetFileName method:
ListBox2.Items.Add(Path.GetFileName(file));
From your comment to #Dennis, this should work.
private void DirSearch(string dir)
{
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
foreach (var file in files)
{
ListBox2.Items.Add(file.Replace(dir, string.empty);
}
}
try recursive method
private void Form1_Load(object sender, EventArgs e)
{
DirSearch(folderBrowserDialog1.SelectedPath);
}
private void DirSearch(string dir)
{
try
{
string userpath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
folderBrowserDialog1.ShowDialog();
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*.*", SearchOption.AllDirectories);
if (!dir.Equals(userpath))
{
foreach (var file in files)
{
listBox1.Items.Add(System.IO.Path.GetFileName(file));
}
IEnumerable<string> dirs = Directory.EnumerateDirectories(dir);
foreach (string dsdir in dirs)
{
DirSearch(dsdir);
}
}
}
catch (Exception ex)
{
}
}