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;
Related
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!
I initially have a Fileupload tool to upload a textfile, manipulate its content and display into a Listbox or Textbox. The limitation however is Fileupload only supports single uploading, at least to the version of .Net Framework I am using.
What I intend to do is just use a button control and remove the Fileupload. Upon Button click I need to read the textfiles inside a designated folder path and display first the contents inside a multiple lined textbox. (not just the file name) This is my intially written codes, and it is not working.
protected void btnGetFiles_Click(object sender, EventArgs e)
{
string content = string.Empty;
DirectoryInfo dinfo = new DirectoryInfo(#"C:\samplePath");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
{
//ListBox1.Items.Add(file.Name);
content += content;
}
txtContent.Text = content;
}
Since your's is web based application you can't access physical paths like c:\\.. you should use Server.MapPath anyway(As per the comment, you don't need to get the file with Server.MapPath). Then for getting the content you can try something like the following:
protected void btnGetFiles_Click(object sender, EventArgs e)
{
try
{
StringBuilder content = new StringBuilder();
if (Directory.Exists(#"C:\samplePath"))
{
// Execute this if the directory exists
foreach (string file in Directory.GetFiles(#"C:\samplePath","*.txt"))
{
// Iterates through the files of type txt in the directories
content.Append(File.ReadAllText(file)); // gives you the conent
}
txtContent.Text = content.ToString();
}
}
catch
{
txtContent.Text = "Something went wrong";
}
}
you wrote content += content;, that is the problem. change it to content += file.Name;, it will work.
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);
}
I am trying to grab the contents of a directory and display each one, on a seperate row of ListBox, the code I have so far is:
private void button10_Click(object sender, EventArgs e)
{
string[] filePaths = Directory.GetFiles(#"folder");
foreach (string path in filePaths)
{
listBox2.Items.AddRange(path + Environment.NewLine);
}
}
You should use Add,not AddRange.
Your code is almost correct; use Add instead of AddRange, and remove the Environment.NewLine.
There are other possible approaches:
AddRange is used to add multiple items at once. So you could do that instead of the loop:
listBox2.Items.AddRange(filePaths);
You could also use data binding:
listBox2.DataSource = filePaths;
Use the following:
listBox2.Items.Add(path);
Or the following:
string[] filePaths = Directory.GetFiles(#"folder");
listBox2.Items.AddRange(filePaths);
I can suggest to you this answer: How to implement glob in C#
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);
}