2 list boxes, 2 files, 2 folders - c#

Im a beginner programmer and im stuck on this project for my internship
Lets say i have hello.txt in folder1 Listbox1 takes it from folder1 and put it in the listbox.
listbox2 does the same thing with folder2 except with a diffrent extension
After for example i have created hello.DOCX i need hello.txt to be removed from listbox1 but not from folder1
i hope this is clear
this is my code to get files from folders
private void LBNietGedaan_Loaded(object sender, RoutedEventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\nour\Desktop\Niet gedaan");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
LB1.Items.Add(file.Name);
}
}
private void LBGedaan_Loaded(object sender, RoutedEventArgs e)
{
//zet files van een folder in de listbox
DirectoryInfo dinfo = new
DirectoryInfo(#"C:\Users\nour\Desktop\Gedaan");
FileInfo[] Files = dinfo.GetFiles("*.DOCX");
foreach (FileInfo file in Files)
{
LB2.Items.Add(file.Name);
}
}

Can't you just make a property with an ObservableCollection or so and then bind the listbox to it? Then you can simply clear it and the listbox will be empty again.
Binding ObservableCollection to WPF ListBox

This is pseudo, so it might need some adjusting, but basically you can but it in a button click, or place it in your first method after you load the list, adjust the variables to match yours.
List<string> one = new List<string>();
foreach (String string1 in LB1.Items)
{
one.Add(string1);
}
List<string> two = new List<string>();
foreach (String string2 in LB2.Items)
{
two.Add(string2);
}
foreach (String string1 in one)
{
foreach (String string2 in two)
{
string cat1 = string1.Substring(0, string1.Length - 4);
string cat2 = string2.Substring(0, string2.Length - 5);
if (cat1.Equals(cat2))
{
LB1.Items.Remove(string1);
// if you want to stop after the first match, break;
// else remove break to find all matches;
break;
}
}
}
Basically this will search the items in listbox1's Items, and remove any file called "yourtarget.txt". I think should send you in the right direction. If you need more let me know!

Related

How can I put listbox text/items into a text file?

So I want to make some sort of management system or list maker. And I want the data to be stored in a text file. Here's what I have.
So when you click then exit button on the form
private void btnExit_Click(object sender, EventArgs e)
{
if (!File.Exists("paste.txt"))
{
}
else if (File.Exists("paste.txt"))
{
File.Delete("paste.txt");
StreamWriter file = new StreamWriter("paste.txt");
string text = listBox1.Text;
file.Write(text);
file.Close();
}
this.Close();
}
So I want it to save all the text in the textbox to a text file. How could I do this? Right now when I click the exit button the file stays blank.
You can use File.WriteAllText. This will overwrite what's in it at all times, so there's no point in deleting it first if that's what you want.
var path = "paste.txt";
var listBoxText = "";
foreach(var item in listBox1.Items)
{
listBoxText += item.ToString() + "\n";
}
if (File.Exists(path))
{
File.WriteAllText(path, listBoxText, Encoding.UTF8);
}
Not sure what your requirements are OP, but if you also want to create the File if doesn't exist, you could do:
var file = new FileInfo(path);
file.Directory.Create(); // will do nothing if it already exists
File.WriteAllText(path, listBox1.Text, Encoding.UTF8);
https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writealltext?view=netframework-4.8
Here is the pretty way of doing it
Lets say you have an item object
public class ListItem
{
public string Value { get; set; }
public string Description { get; set; }
public string DisplayValue
{
get
{
return $"[{Value}] - {Description}";
}
}
}
You see, I provided an object that could be like that, more complex object, but could be just a string.
When you add objects you create a list and do something like this
var itemList = new List<ListItem>();
// add items
myLst.DisplayMember = "DisplayValue";
myLst.ValueMember = "Value";
myLst.DataSourse = itemList;
In this case you can get the list of "any property" like this (System.Linq)
string[] fileLines =
((List<ListItem>)myLst.DataSourse).Select(itm => itm.Value).ToArray();
Or, if your items are simple strings
string[] fileLines = (from itm in myLst.Items select itm).ToArray();
And then use your file logic to simply in the end call
File.WriteAllLines(path, fileLines);
What I like about this approach is that no explicit loops needs and item can be a more complex item that can have a bunch of properties beyond a simple string description/value in one.

ComboBox showing file names

I have created a comboBox inside a Windows Form and inside this comboBox I want to show filenames inside a specific directory.
My code Form 1:
private string path = (#"C:\Users\khaab\Documents\visual studio 2015\Projects\ReadingXML\ReadingXML\bin\Debug\Customers");
private void SelectConfigComboBox_DropDown(object sender, EventArgs e)
{
List<String> Configurations = Directory.EnumerateDirectories(path).ToList();
Path.GetFileName(path);
SelectConfigComboBox.DataSource = Configurations;
}
My problem at this moment is that when I click on the ComboBox it shows me the whole path name I want only the names of the file inside that directory.
after enumerating all files apply Path.GetFileName method to each of them using Select extension method:
private void SelectConfigComboBox_DropDown(object sender, EventArgs e)
{
List<String> Configurations = Directory.EnumerateFiles(path)
.Select(p => Path.GetFileName(p))
.ToList();
SelectConfigComboBox.DataSource = Configurations;
}
Get all fileEntries (full path), and then use Path.GetFileName() to obtain only the filename of each:
List<String> Configurations = new List<string>();
string [] fileEntries = Directory.GetFiles(path);
foreach(string fileName in fileEntries)
{
Configurations.Add(Path.GetFileName(fileName);
}
SelectConfigComboBox.DataSource = Configurations;
Before set DataSource use Path.GetFileName for items in result of Directory.EnumerateDirectories(path).ToList()
FileInfo has a Name property that only contains the filename part.
var files= new DirectoryInfo(path).GetFiles("*");
var firstFilename = files[0].Name;

Adding Menu Subitems By Getting File Names from Directory

Code:
private void loadViewTemplates(string path)
{
foreach (string file in Directory.GetFiles(path, "*.txt"))
{
ToolStripItem subItem = new ToolStripMenuItem();
viewTemplatesToolStripMenuItem.DropDownItems.Add(subItem);
}
}
I have three files in the source directory, they seem to appear as the menu subitem, but the file names did not appear.
Is there a way I can make the file names' appear instead of invisible? Your help would be much appreciated. Thank you!
Missing the
subItem.Text = Path.GetFileNameWithoutExtension(file);
From MSDN
ToolStripItem.Text - Gets or sets the text that is to be displayed on the item.
So the code will be
private void loadViewTemplates(string path)
{
foreach (string file in Directory.GetFiles(path, "*.txt"))
{
ToolStripItem subItem = new ToolStripMenuItem();
subItem.Text = Path.GetFileNameWithoutExtension(file);
viewTemplatesToolStripMenuItem.DropDownItems.Add(subItem);
}
}
I have found a solution myself as below:
private void loadViewTemplates(string path)
{
foreach (string file in Directory.GetFiles(path, "*.txt"))
{
viewTemplatesToolStripMenuItem.DropDownItems.Add(Path.GetFileNameWithoutExtension(file));
}
}
Thank you.

Dynamically adding LinkLabels to a TableLayoutPanel

I've been having a problem with the following code:
namespace Viewer
{
public partial class Form1 : Form
{
int count = 0;
LinkLabel[] linkLabel = new LinkLabel[200];
string filename;
string extension;
string filepath;
private void btnLoad_Click(object sender, EventArgs e)
{
// Creates a Directory for the Movies Folder
DirectoryInfo myDirectory = new DirectoryInfo(#"C:\Users\User\Movies");
// Creates a list of "File info" objects
List<FileInfo> ls = new List<FileInfo>();
// Adds filetypes to the list
ls.AddRange(myDirectory.GetFiles("*.mp4"));
ls.AddRange(myDirectory.GetFiles("*.avi"));
// Orders the list by Name
List<FileInfo> orderedList = ls.OrderBy(x => x.Name).ToList();
// Loop through file list to act on each item
foreach (FileInfo filFile in orderedList)
{
// Creates a new link label
linkLabel[count] = new LinkLabel();
// Alters name info for display and file calling
filepath = filFile.FullName;
extension = filFile.Extension;
filename = filFile.Name.Remove(filFile.Name.Length - extension.Length);
// Write to the textbox for functional display
textBox1.AppendText(filename + "\r\n");
// Alters link label settings
linkLabel[count].Text = filename;
linkLabel[count].Links.Add(0, linkLabel[count].Text.ToString().Length, filepath);
linkLabel[count].LinkClicked += new LinkLabelLinkClickedEventHandler(LinkedLabelClicked);
// Adds link label to table display
tblDisplay.Controls.Add(linkLabel[count]);
// Indexes count up for arrays
count = count + 1;
}
}
private void LinkedLabelClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start(filepath);
}
}
}
My goal is to generate a table of links to all of the media files that I add at launch, and have the links open the files in their respective players.
As of right now, it generates all of the links properly, but whenever I click on any of them, it launches the last item in the list.
For example, if the list contains "300", "Gladiator", and "Top Gun", no matter which link I click, it opens "Top Gun".
I assume that this has to do with it calling the variable "filepath" in the click event, which is left in it's final state. However, I'm not exactly clear on how to create a static link value or action on each individual link, as all of the answers I've researched are in regards to single linklabel situations, not dynamic set-ups.
Any help/advice would be appreciated!
Try as below:
In foreach loop add one line more like:
linkLabel[count].Tag = filepath;
then in click event get this path as blow,
private void LinkedLabelClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
string filepath = ((LinkLabel)sender).Tag.tostring();
System.Diagnostics.Process.Start(filepath);
}

How to fill a Combo Box on C# with the namefiles from a Dir?

I hope you can help me with this problem.
I've been trying to fill a combobox with the namefiles of a specific directory. This DIR will be always the same so it will be the same routine always.
Any ideas?
Cheers!
string[] filePaths = Directory.GetFiles(#"c:\MyDir\", "*.txt");
foreach (string file in filePaths)
{
mycombobox.items.add(file);
}
When you initialize do this:
private void Form1_Load(object sender, EventArgs e)
{
string[] files = System.IO.Directory.GetFiles(#"C:\Testing");
this.comboBox1.Items.AddRange(files);
}
Or if you are using WPF
<Grid>
<ComboBox x:Name="DirectoriesComboBox" Width="100" Height="25"></ComboBox>
</Grid>
string [] array = Directory.GetFiles(#"C:\Test");
DirectoriesComboBox.ItemsSource = array;
You can do so by adding a reference to system.IO and using this code:
(DDLFolder is you dropdown list, and if you are writing an ASP.Net application for getting the path use Server.Mappath("~/yourpath"))
DirectoryInfo df = new DirectoryInfo(userFolderPath);
DDLFolder.Items.Clear();
DDLFolder.Items.Add("Root");
foreach (DirectoryInfo d in df.GetDirectories())
{
DDLFolder.Items.Add(d.Name);
}

Categories

Resources