What should be in (???)
I want to open for example 3 selected files in my simple file explorer
private void Open_Click(object sender, System.EventArgs e)
{
foreach (???)
{
string ImageViewName = listView1.SelectedItems[0].Text;
System.Diagnostics.Process.Start(#textBox1.Text.Remove(3, 1) + "/" + ImageViewName);
}
}
in textbox1 is my path to the files
Assuming each File is in a List called Files
foreach (File myFile in Files){
//Do something with myFile
}
The foreach block will iterate through each File in Files. The current selected file, which can be accessed from within the foreach block, is called 'myFile' in this instance.
I am new to stackoverflow so I'm open to advice about my answer too!
Related
Is it possible to store the files that you have opened using OpenFileDialog in WPF? Currently, I have this code that opens a file from the computer and shows the directory of it in a listBox:
private void UploadEmployeeRank1_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (openFileDialog.ShowDialog() == true)
{
foreach (string filename in openFileDialog.FileNames)
employeeRank1PrivateMaterialsListBox.Items.Add(filename);
}
}
However, once I close the application and open in again, the file that I have loaded in the listBox is gone. How do I make it stay?
OpenFileDialog does not actually load the files. It returns you the path of the selected files. So at the end you will just need to save those strings.
One simple and quick way is to write them in local file.
Here are two functions that will save and load file paths in a file.
private void SaveFiles()
{
if (listBox1.Items.Count > 0)
{
StringBuilder files = new StringBuilder();
foreach (var file in listBox1.Items)
{
files.AppendLine(file.ToString());
}
File.WriteAllText("myfiles.txt", files.ToString());
}
}
private void LoadFiles()
{
if (File.Exists("myfiles.txt"))
{
string[] files = File.ReadAllLines("myfiles.txt");
listBox1.Items.AddRange(files);
}
}
SaveFiles() function loads the files from your listbox and saves each path as a new line in text file.
LoadFiles() function parses the file and loads the data in your listbox.
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);
I'm getting an unhandled exception of type System.IO.IOException occurring in mscorlib.dll because the file I'm trying to delete is being used by another process.
I want it to skip the used files.
private void button1_Click(object sender, EventArgs e)
{
System.IO.DirectoryInfo directory =
new System.IO.DirectoryInfo(#"C:\Users\fatih\AppData\Local\Temp");
foreach (System.IO.FileInfo file in directory.GetFiles()) file.Delete();
foreach (System.IO.DirectoryInfo subDirectory in directory.GetDirectories())
subDirectory.Delete(true);
}
If it's not important that you delete everything, use:
private void button1_Click(object sender, EventArgs e)
{
string directory = #"C:\Users\fatih\AppData\Local\Temp";
deleteDirectory(directory);
}
private void deleteDirectory(string directory){
foreach (string file in Directory.GetFiles(directory))
{
try{
File.Delete(file);
}
catch(Exception e0){
Console.WriteLine(e0.Message+"\n"+e0.Source);//not necessary but nice to learn from
}
}
foreach (string direc in Directory.GetDirectories(directory)) {
deleteDirectory(direc);
Directory.Delete(direc,true);
}
}
This will simply skip over any file or directory that has a problem and delete everything else.
Use the static versions of the directory and file methods, you cannot use a foreach on file.delete the way you are doing it because you are trying to do a delete operation on the thing you are looping through.
foreach (var file in Directory.GetFiles(directory))
{
File.Delete(file);
}
Update: I did not notice the subdirectory delete, that is your issue, if you want to just delete everything including the directory you are on, then you are working too hard.
Directory.Delete(Directory, true);
Will wipe out the directory and all the subdirectories and files in the directory passed in.
Since you are still having issues, and everyone seems to think I am wrong here, I will give you the code to past into your solution.
private void button1_Click(object sender, EventArgs e)
{
string directory = #"C:\Users\fatih\AppData\Local\Temp")
Directory.Delete(directory, true);
}
IF there is an outside process hanging on to the file this will not work, otherwise it will do what you want it to do
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
I'm not sure whether this topics has been disscussed before or not, but I'm not sure the exact word to search for it. What method/class should I use?
The program has 3 buttons: 1) for folder browsing, 2) scan for the selected folder content, and 3) open the file. When user browse the selected folder**(1), user click scan button to scan from the first file until the last available files and listed it text box(2)** and from that user can decide whether to open the files or not**(3)**.
Here are what have I done so far (no 1 and 3):
//For browse.
private void browse2()
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
this.txtDest.Text = folderBrowserDialog1.SelectedPath;
}
}
//For opening folder.
private void btnOpen_Click(object sender, EventArgs e)
{
try
{
Process.Start(txtDest.Text);
}
catch
{
MessageBox.Show("Please select one file/folder");
}
}
If you are trying to just open a file you can directly use an Open File Dialog.
If you need to display the contents of a directory you can use the Directory Info Class.
Well my example is a WPF app that adds files/ folders in a directory to a treeview, but you should get the general idea:
Note: Code was written for a training exercise, and therefore only goes 3 levels deep, as a proof of concept kind of thing
private void Window_Loaded(object sender, RoutedEventArgs e)
{
foreach (DriveInfo di in DriveInfo.GetDrives())
{
TreeViewItem drive = new TreeViewItem();
drive.Header = di.Name;
treeView1.Items.Add(drive);
DirectoryInfo folders = new DirectoryInfo(di.Name);
// The depth count means that it only goes 3 levels deep, to make it quick to load
GetFoldersAndFiles(drive, folders, 3);
}
}
private static void GetFoldersAndFiles(TreeViewItem parent, DirectoryInfo folders, int depth)
{
if ((depth > 0)
{
foreach (DirectoryInfo dirI in folders.GetDirectories())
{
TreeViewItem dir = new TreeViewItem();
dir.Header = dirI.Name;
parent.Items.Add(dir);
GetFoldersAndFiles(dir, dirI, depth - 1);
}
foreach (FileInfo fileI in folders.GetFiles())
{
TreeViewItem file = new TreeViewItem();
file.Header = fileI.Name;
parent.Items.Add(file);
}
}
}