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

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

Related

Directory Getfiles not working as I expected

I am using express VS-2015.I have an folderbrowser control,textbox1 and button control.
I need to retrieve multiple file type and show it on listbox.I am wondering what is wrong in my code.It is not showing any error but not showing any files, despite of file type present in a folder.any suggestion.
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 Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
//notification to user
return;
}
string[] extensions = { ".xml", ".ddg" };
string[] dizin = Directory.GetFiles(textBox1.Text, "*.*", SearchOption.AllDirectories)
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
listBox1.Items.AddRange(dizin);
}

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.

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

IO Exception was unhandled. The process cannot access the file because it is being used

I wrote a program, code seems working but it is not working. It gives IO exception was unhandled error. Some guys say me , you should delete something because program try to use same file at the same time. Please help me!!
namespace App1508
{
public partial class Form2 : Form
{
string goodDir = "C:\\GOOD\\";
string badDir = "C:\\BAD\\";
string fromDir = "C:\\DENEME\\";
List<Image> images = null;
int index = -1;
FileInfo[] finfos = null;
public Form2()
{
InitializeComponent();
DirectoryInfo di = new DirectoryInfo(#"C:\DENEME");
finfos = di.GetFiles("*.jpg",SearchOption.TopDirectoryOnly);
images = new List<Image>();
foreach (FileInfo fi in finfos)
{
images.Add(Image.FromFile(fi.FullName));
}
}
private void button1_Click(object sender, EventArgs e)
{
finfos[index].MoveTo(Path.Combine("C:\\GOOD", finfos[index].Name));
}
private void pictureBox1_Click(object sender, EventArgs e)
{
index++;
if (index < 0 || index >= images.Count)
index = 0;
pictureBox1.Image = images[index];
}
private void button2_Click(object sender, EventArgs e)
{
finfos[index].MoveTo(Path.Combine("C:\\BAD", finfos[index].Name));
}
}
}
This is the problem:
foreach (FileInfo fi in finfos)
{
images.Add(Image.FromFile(fi.FullName));
}
Image.FromFile will open a file handle, and won't close it until you dispose of the image. You're trying to move the file without disposing of the image which has that file open first.
I suspect if you dispose of the relevant image in your button1_Click and button2_Click methods (being aware that if it's showing in the PictureBox you'll need to remove it from there first) you'll find it works.
Ref:
http://support.microsoft.com/?id=814675

Display only image file extensions within a Listbox

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

Categories