Filling Combo/ListBox with file names from a directory - c#

I'm attempting to populate a ListBox with file names from a directory. My code works, however, when I recompile the program the items are no longer there. Also when I click on an item in the ListBox the content of the ListBox is duplicated over and over. Any guidance would be much appreciated, thanks.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo(".\\Notes\\");
FileInfo[] files = dir.GetFiles("*.txt");
foreach ( FileInfo file in files )
{
listBox1.Items.Add(file);
}
}

You've populated your ListBox in the incorrect event. So each time you select an item, the ListBox is populated again. You should put it in another event like Button_Click or Form_load:
private void Form1_Load(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo(".\\Notes\\");
FileInfo[] files = dir.GetFiles("*.txt");
foreach ( FileInfo file in files )
{
listBox1.Items.Add(file);
}
}
//Or in a Button_Click event
private void button1_Click(object sender, EventArgs e)
{
DirectoryInfo dir = new DirectoryInfo(".\\Notes\\");
....
}

So thanks to the advice of #S.Akbari my solution to my issue is below.
public Form1()
{
InitializeComponent();
DirectoryInfo dir = new DirectoryInfo(".\\Notes\\");
FileInfo[] files = dir.GetFiles("*.txt");
foreach (FileInfo file in files)
{
listBox1.Items.Add(file);
}
}

Related

Files without extensions in listbox

1.) How I can remove file extension (".txt")?
2.) Why when I click somewhere to listbox window so all items are replicated???
private void listBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Folder");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
listBox1.Items.Add(file.Name);
}
}
listBox.Items.Clear(); // to clear current listbox items
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
listBox1.Items.Add(Path.GetFileNameWithoutExtension(file.Name));
}

Show file names in listbox for selected directory in treeview

I have a button "Choose folder". When i choose folder, it shows all the directories and sub-directories in treeview. Everything is working fine.
What i need now is - when i click in the treeview on some directory in shows all files that is in that directory in the listbox.
private void button1_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
DirectoryInfo directoryInfo = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
if (directoryInfo.Exists)
{
VeidotKoku(directoryInfo, treeView1.Nodes);
}
}
}
private void VeidotKoku(DirectoryInfo directoryInfo, TreeNodeCollection Pievienot)
{
TreeNode tagadejaNode = Pievienot.Add(directoryInfo.Name);
foreach (DirectoryInfo subdir in directoryInfo.GetDirectories())
{
VeidotKoku(subdir, tagadejaNode.Nodes);
}
}
System.IO.Path.GetFileNameWithoutExtension(fileLocationPath);
Will get the extensionless path.
Else, if you just want to get the value you can split the path and get the last element.
foreach(string filePath in filePaths)
{
string[] brokenPath = filePath.Split('/');
listBox.Add(brokenPath.Last());
}
Top of my head.

How to view selected item in listbox in image viewer asp.net

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.

File not found error from the listbox C# win forms

I have a listbox and it has some files loaded from a directory folder.
Code to load the files into the listBox1:
private void Form1_Load(object sender, EventArgs e)
{
PopulateListBox(listbox1, #"C:\TestLoadFiles", "*.rtld");
}
private void PopulateListBox(ListBox lsb, string Folder, string FileType)
{
DirectoryInfo dinfo = new DirectoryInfo(Folder);
FileInfo[] Files = dinfo.GetFiles(FileType);
foreach (FileInfo file in Files)
{
lsb.Items.Add(file.Name);
}
}
I want to read and display the attributes values to the labels in the form. The loaded files in the listBox1, here is the code:
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
string path = (string)listBox1.SelectedItem;
DisplayFile(path);
}
private void DisplayFile(string path)
{
string xmldoc = File.ReadAllText(path);
using (XmlReader reader = XmlReader.Create(xmldoc))
{
while (reader.MoveToNextAttribute())
{
switch (reader.Name)
{
case "description":
if (!string.IsNullOrEmpty(reader.Value))
label5.Text = reader.Value; // your label name
break;
case "sourceId":
if (!string.IsNullOrEmpty(reader.Value))
label6.Text = reader.Value; // your label name
break;
// ... continue for each label
}
}
}
}
Problem:When I click on the file in the listBox1 after the form is loaded,the files are loaded from the folder into the listbox but it's throwing an error File not found in the directory.
How can I fix this problem???
That is because you are adding File.Name instead you should add File.FullName in your listbox
lsb.Items.Add(file.FullName);
so your method PopulateListBox should become:
private void PopulateListBox(ListBox lsb, string Folder, string FileType)
{
DirectoryInfo dinfo = new DirectoryInfo(Folder);
FileInfo[] Files = dinfo.GetFiles(FileType);
foreach (FileInfo file in Files)
{
lsb.Items.Add(file.FullName);
}
}
EDIT:
It looks like you want to display only the file name, not the full path. You could follow a following approach. In PopulateListBox, add file instead of file.FullName so the line should be
foreach (FileInfo file in Files)
{
lsb.Items.Add(file);
}
Then in SelectedIndexChanged event do the following:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
FileInfo file = (FileInfo)listbox1.SelectedItem;
DisplayFile(file.FullName);
}
This should get you the full name (file name with path) and will resolve your exception of File Not Found
The problem you are facing is that in the listbox you only specify the file name, and not the entire file path and name, so when it looks for the file you it cant find it.
From FileInfo.Name Property
Gets the name of the file.
Whereas File.ReadAllText Method (String) takes path as a parameter.
You are not specifying the full path.
Try something like this:
DisplayFile(#"C:\TestLoadFiles\" + path)

C# drag and drop files to form

How could I load files to a form by drag-and-drop?
Which event will appear?
Which component should I use?
And how to determine name of file and others properties after drag-and-dropping it to a form?
Thank you!
Code
private void panel1_DragEnter(object sender, DragEventsArgs e){
if (e.Data.GetDataPresent(DataFormats.Text)){
e.Effect = DragDropEffects.Move;
MessageBox.Show(e.Data.GetData(DataFormats.Text).toString());
}
if (e.Data.GetDataPresent(DataFormats.FileDrop)){
}
}
ok, this works.
How about files? How can I get filename and extension?
and this is only a dragEnter action.
This code will loop through and print the full names (including extensions) of all the files dragged into your window:
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string filePath in files)
{
Console.WriteLine(filePath);
}
}
Check the below link for more info
http://doitdotnet.wordpress.com/2011/12/18/drag-and-drop-files-into-winforms/
private void Form2_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] filePaths = (string[])(e.Data.GetData(DataFormats.FileDrop));
foreach (string fileLoc in filePaths)
// Code to read the contents of the text file
if (File.Exists(fileLoc))
using (TextReader tr = new StreamReader(fileLoc))
{
MessageBox.Show(tr.ReadToEnd());
}
}
}
You need work with 2 below Events, of course while your Control/Form AllowDrop property's is true.
private void Home_DragOver(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Link;
else
e.Effect = DragDropEffects.None;
}
private void Home_DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
//YourOpenMethod(files);
}
}
Enjoy...

Categories