So basically what I'm trying to accomplish is being able to select a file from a displayed list and open that file. Right now I have it set up in a CheckBoxList that displays the .docx, .mov, and .txt files that exist in the selected folder. The problem is I can't get it to open the file. I've seen most people suggesting-
Process.Start(filename);
But the problem with that is that it requires a specific file name and I'm trying to pull that name from a variable. Any ideas?
Here's my current code -
private void Form1_Load(object sender, EventArgs e)
{
const string path = #"C:\Users\Haxelle\Documents\Journal";
List<string> extensions = new List<string> { "DOCX", "MOV", "TXT" };
string[] files = GetFilesWithExtensions(path, extensions);
ckbEntry.Items.AddRange(files);
}
private string[] GetFilesWithExtensions(string path, List<string> extensions)
{
string[] allFilesInFolder = Directory.GetFiles(path);
return allFilesInFolder.Where(f => extensions.Contains(f.ToUpper().Split('.').Last())).ToArray();
}
private void btnOpen_Click(object sender, EventArgs e)
{
CheckedListBox.CheckedItemCollection selectedFiles = ckbEntry.CheckedItems;
}
Trying to open file in btnOpen_Click
It seems like all you are missing is iterating over the selected files names and opening them. Since the CheckedItemCollection.Item is typed as object, you will need to cast the items, which can be done using LINQ's Cast function.
private void btnOpen_Click(object sender, EventArgs e)
{
CheckedListBox.CheckedItemCollection selectedFiles = ckbEntry.CheckedItems;
foreach (var filename in selectedFiles.Cast<string>()) {
Process.Start(filename);
}
}
Related
I have a WinForms application where I allow users to drag and drop images onto a panel. For now, they need to drop two files at once to add them both. If they drop one and then they want to add another, it just overwrites the first file.
I want to allow them to drop one file at once, and add as many as they want without overwriting them.
private void Panel1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
string[] files;
private void Panel1_DragDrop(object sender, DragEventArgs e)
{
files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
Console.WriteLine(files.Length);
}
}
The reason it doesn't work is that you're throwing away whatever is in files every time DragDrop is raised. Instead of using an array, you should use List<string> (or HashSet<string> to ignore duplicates).
Here's an example:
List<string> files = new List<string>();
private void Panel1_DragDrop(object sender, DragEventArgs e)
{
files.AddRange((string[])e.Data.GetData(DataFormats.FileDrop));
Console.WriteLine(files.Count);
}
Or with HashSet:
HashSet<string> files = new HashSet<string>();
private void Panel1_DragDrop(object sender, DragEventArgs e)
{
files.UnionWith((string[])e.Data.GetData(DataFormats.FileDrop));
Console.WriteLine(files.Count);
}
I failed to fill combobox with csv filenames. I created the combobox by dragging from toolbox in Microsoft Visual Studio. I set the name of combobox to ChooseSampleSheet.
The following is my code:
private void ChooseSampleSheet_SelectedIndexChanged(object sender, EventArgs e)
{
DirectoryInfo d = new DirectoryInfo(#"C:\Users\UniFlow\Desktop\Europa-master\user interface\Europa design Y\Experiemnt_Gui");//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.csv"); //Getting Text files
ChooseSampleSheet.DataSource = Files;
ChooseSampleSheet.DisplayMember = "Name";
}
Also, I tried the following code:
private string path = (#"C:\Users\UniFlow\Desktop\Europa-master\user interface\Europa design Y\Experiemnt_Gui");
private void ChooseSampleSheet_SelectedIndexChanged(object sender, EventArgs e)
{
List<String> Configurations = Directory.EnumerateDirectories(path, "*.exe")
.Select(p => Path.GetFileName(p))
.ToList();
ChooseSampleSheet.DataSource = Configurations;
}
But Neither of them works. Nothing shows in my combobox. I expected to see csv file names. So that I can click to open selected file afterwards (not show in in my code).
People suggested me to change the event. The following is my update.
private void form4_load(object sender, EventArgs e)
{
DirectoryInfo d = new DirectoryInfo(#"C:\Users\UniFlow\Desktop\Europa-master\user interface\Europa design Y\Experiemnt_Gui");//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.csv"); //Getting Text files
ChooseSampleSheet.DataSource = Files;
ChooseSampleSheet.DisplayMember = "Name";
}
private void ChooseSampleSheet_SelectedIndexChanged(object sender, EventArgs e)
{
}
However, nothing show in the combobox still.
I do not see anything wrong in your code however I think your code is at the wrong place.
SelectedIndexChanged will get execute when you select something from the drop down. Since your drop down has not been filled with values , you can't fire that event.
Put the same code in form_load and you will see the values there.
DirectoryInfo d = new DirectoryInfo(#"C:\Users\UniFlow\Desktop\Europa-master\user interface\Europa design Y\Experiemnt_Gui");//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.csv"); //Getting Text files
ChooseSampleSheet.DataSource = Files;
ChooseSampleSheet.DisplayMember = "Name";
I am making a program in which users can modify remote files. I put the selected files (depending on some predefined criteria) in a listView, but I display only the file names, not full filepaths.
The problem I get however, is that when a user would double-click on an item, it should open another window to modify that item.
private void listView1_DoubleClick(object sender, EventArgs e)
{
account = File.ReadAllLines("\\\\myremoteserver\\ftp\\"+listView1.SelectedItems[0].Text+".txt");
Form3 passForm = new Form3();
passForm.ShowDialog();
}
private void Form2_Load(object sender, EventArgs e)
{
string[] files = Directory.GetFiles("\\\\myremotserver\\ftp\\","*.txt", System.IO.SearchOption.AllDirectories);
foreach (string s in files)
{
listView1.Items.Add(Path.GetFileNameWithoutExtension(s));
}
}
The problem is, that the files are all in different subfolders, so if I leave the code as is, it will not display the correct content of the file. For example, the file is called test1.txt, it is placed in myremoteserver\ftp\testfolder\test1.txt, but with my program, it will try to find the file in myremoteserver\ftp\test1.txt.
What I am asking is, if it is possible to modify the listView in such a way, that the full file path is always saved, but only the file names are displayed? I do not want the user to see the complete file path of the files, just the file names.
Use the Tag property of the ListViewItem
So to create items...
foreach (string s in files)
{
ListViewItem lvi = new ListViewItem(Path.GetFileNameWithoutExtension(s));
lvi.Tag = s;
listView1.Items.Add(lvi);
}
Then in event handler...
account = File.ReadAllLines("\\\\myremoteserver\\ftp\\"+listView1.SelectedItems[0].Tag +".txt);
Essentially I have a button and a text box and when the user inputs text and hits the button i want it to create anew folder in a selected destination, ive got my code currently and cant figure out why it wont work
private void button1_Click(object sender, EventArgs e)
{
if (!Directory.Exists("C:\\Users\\Ben\\Documents\\CreateDirectoryTest" + Searchbox.Text))
{
Directory.CreateDirectory("C:\\Users\\Ben\\Documents\\CreateDirectoryTest" + Searchbox.Text);
}
}
am i missing something? help would be really appreciated
Don't concatenate file system path's manually. Use the methods of System.IO:
private void button1_Click(object sender, EventArgs e)
{
const string path = "C:\\Users\\Ben\\Documents\\CreateDirectoryTest\\";
var directory = System.IO.Path.Combine(path, Searchbox.Text);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
}
I assume you're trying to check for a subdirectory of CreateDirectoryTest and create a directory inside of it if not. The way you're concatenating the string, if Searchbox.text is "TheFolder" for example, your string would end up looking like this:
C:\Users\Ben\Documents\CreateDirectoryTestTheFolder
You can either add a \\
if (!Directory.Exists("C:\\Users\\Ben\\Documents\\CreateDirectoryTest\\" + Searchbox.Text))
{
Directory.CreateDirectory("C:\\Users\\Ben\\Documents\\CreateDirectoryTest\\" + Searchbox.Text);
}
Or just use Path.Combine:
string path = System.IO.Path.Combine("C:\\Users\\Ben\\Documents\\CreateDirectoryTest", Searchbox.Text);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
I want to reduce the length of the path and display only the file name.
For example, suppose the path is c:\\program files\...\123.jpg I want to display only 123.jpg.
Here is the code I have been working with thus far. Can anyone suggest modifications?
private void button1_Click(object sender, EventArgs e)
{
panel3.Controls.Clear();
var ofd = new OpenFileDialog();
ofd.Multiselect = true;
ofd.Filter = "DICOM Files (*.dcm;*.dic)|*.dcm;*.dic|All Files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.Cancel)
return;
foreach (string s in ofd.FileNames)
{
listBox1.Items.Add(s);
}
}
There is a class named Path in System.IO namespace.
Between its numerous static methods you could find
Path.GetFilename(string);
Using it in your Add loop you could set only the filenames
listBox1.Items.Add(Path.GetFileName(s));
However, I suggest to save the folder name somewhere, because if you need to process these files you need it. And, guess what, Path has a method also to extract a path from a full filename
if(filenames.Length > 0)
string workingPath = Path.GetDirectoryName(filenames[0]);
EDIT
From your comments below it seems that you call this button_click more than one time and every time you select a different folder. In this case, stripping the path part from the selected filenames leaves your listbox filled with files that you can't retrieve because you don't know the path part (stripped away). If you need to retrieve the files selected to execute some kind of process, then you need to store somewhere the full path of these files and be able to retrive them.
You can achieve this result storing the files selected in a List<string> instance.
Declare at the global level a variable to store these full filenames
(Add using System.Collection.Generic;)
List<string> selectedFiles = new List<string>();
Now inside the button click add the full filename to the List<string> and the stripped file to the ListBox items, in the same order
private void button1_Click(object sender, EventArgs e)
{
panel3.Controls.Clear();
var ofd = new OpenFileDialog();
ofd.Multiselect = true;
ofd.Filter = "DICOM Files (*.dcm;*.dic)|*.dcm;*.dic|All Files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.Cancel)
return;
foreach (string s in ofd.FileNames)
{
listBox1.Items.Add(Path.GetFileName(s));
selectedFiles.Add(s);
}
}
Now, if you want to retrieve the full path for the selected file in the listbox you could use
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
if(listBox1.SelectedIndex >= 0)
{
string fullFileName = selectedFiles[listBox1.SelectedIndex];
.... process the filename ....
}
}
Use Path.GetFileName() to return the name
see http://msdn.microsoft.com/en-us/library/system.io.path.getfilename(v=vs.110).aspx