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
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.
Still new to C#, snipping some code around to write a simple application and learning while doing.
I have an xml file that needs to be ingested and set as a variable so I can have it just insert words from that text file into different text fields.
private void button1_Click(object sender, EventArgs e)
{
// Displays an OpenFileDialog so the user can select a datafeed.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Datafeed File|*.dfx5";
openFileDialog1.Title = "Select a dfx5";
// Show the Dialog.
// If the user clicked OK in the dialog and
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Assign the file as a variable.
}
}
How would I make that file a variable so that I can read from it?
Thank you in advanced. Google-ing didn't return anything helpful
How would I make that file a variable so that I can read from it?
Well, the file name that was selected is a property of the OpenFileDialog object:
string fileName;
// Show the Dialog.
// If the user clicked OK in the dialog and
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// Assign the file as a variable.
fileName = openFileDialog1.FileName;
}
What you do with that file name at that point is up to you.
If you want to store the Filename in a variable, the other answers are what you are looking for.
To me it sounds like you need to actually read the content of the file.
If that's what you want, the following snippet (provided by Microsoft) should do:
try
{ // Open the text file using a stream reader.
using (StreamReader sr = new StreamReader(openFileDialog1.FileName))
{
// Read the stream to a string, and write the string to the console.
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
This way line will contain the XML data you need. How you proceed from there is up to you.
If the file is pure XML, then I'd be inclined to do something like this:
using System.Xml.Linq;
private XDocument _xmlPayload;
private void button1_Click(object sender, EventArgs e)
{
// Displays an OpenFileDialog so the user can select a datafeed.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Datafeed File|*.dfx5";
openFileDialog1.Title = "Select a dfx5";
// Show the Dialog.
// If the user clicked OK in the dialog and
var dialogResult = openFileDialog1.ShowDialog();
if (dialogResult == System.Windows.Forms.DialogResult.OK)
{
//Get file path from dialog
var filePath = openFileDialog1.FileName;
//load xml
using(var stream = File.OpenRead(filePath))
{
_xmlPayload = XDocument.Load(stream);
}
}
}
Then it's up to you how you work with the XML.
openFileDialog1.FileName should have the returned filename from the dialog. if multiselect is enabled I think its openFileDialog1.FileNames
I'm looking for an option that allows a user to input their destination folder (Usually copy/Paste) into a text box on a Windows Application, and append the file's name with a specific name. However, I'm stuck as to how to accomplish this.
//Exporting to CSV.
string folderPath = MessageBox.Show(textBox1_TextChanged);
File.WriteAllText(folderPath + "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv", csv);
So it can look like: C:/DIR_9132017.csv, or Documents/DIR_9132017.csv, depending on what the user inputs into the textbox. I have nothing in my textbox code section at the moment, if that also gives a clearer picture about the situation.
Any help will be greatly appreciated. Thank you!
You can either use FolderBrowserDialog or can just copy/paste the path and create the directory.
Using FolderBrowserDialog
Step1 : Create Browse button (so that the user can choose the directory)
Step2 : Create Export button (Place the code to write the file here)
private void browseButton_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
var folderPath = folderBrowserDialog1.SelectedPath;
textBox1.Text = folderPath;
}
}
private void exportToCsvButton_Click(object sender, EventArgs e)
{
var path = textBox1.Text;
var file = Directory.CreateDirectory(path);
var filename = "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv";
File.WriteAllText(Path.Combine(path, "test.csv"), "content");
}
Using Copy/Paste
Step1 : Create Export button (User copy pastes the path. System create the directory and writes the file)
private void exportToCsvButton_Click(object sender, EventArgs e)
{
var path = textBox1.Text;
var file = Directory.CreateDirectory(path);
var filename = "DIR_" + (DateTime.Now.ToShortDateString()) + ".csv";
File.WriteAllText(Path.Combine(path, "test.csv"), "content");
}
You would use a FolderBrowserDialog for that. After adding it to your form, you can use it like this:
public void ChooseFolder()
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
folderPath = folderBrowserDialog1.SelectedPath;
}
}
Source: https://msdn.microsoft.com/en-us/library/aa984305(v=vs.71).aspx
You haven't specified whether it's WinForms or WPF, so I'm using WPF, but is should be the same in WinForms.
To select the folder, you could use FolderBrowseDialog as follows. This code should be placed inside a button or some other similar control's Click event.
if (folderBrowse.ShowDialog() == DialogResult.OK)
{
txtPath.Text = folderBrowse.SelectedPath;
}
txtPath being a TextBox your selected path displayed in. You can substitute it with a simple string variable if you don't want to use a TextBox.
And if you want the user to be able to drag-drop a folder into a TextBox, you can create a TextBox control, and in it's PreviewDragOver and Drop events, you can do the following.
private void txtPath_PreviewDragOver(object sender, DragEventArgs e)
{
e.Handled = true;
}
private void txtPath_Drop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
if (files != null && files.Length != 0)
txtPath.Text = files[0];
}
Using both above in combination user has the ability to either select the folder he/she wants by clicking a button, drag-and-drop a folder into the TextBox, or copy-paste the folder path into the TextBox.
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 developing a tool that processes an .fbx model and user input into a single file for use in a game. The code for when the user presses the "Import Model" button is as follows, and is similar for every button:
private void E_ImportModelButton_Click_1(object sender, EventArgs e)
{
E_model = null; // byte array where model is stored
E_SelectedFileLabel.Text = "No Model Selected"; // label on form
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "FBX Model (.fbx)|*.fbx";
ofd.Multiselect = false;
if (ofd.ShowDialog() == DialogResult.OK)
{
// adjusts variables for game file
string s = Path.GetDirectoryName(ofd.FileName);
E_model = File.ReadAllBytes(s);
E_SelectedFileLabel.Text = "File Selected: " + ofd.FileName;
}
}
The problem is, whenever I click OK, an UnauthorizedAccessException occurs. I have tried importing files from C:\Users\Owner\Downloads as well as C:\Users\Owner\Desktop and the C:\ drive itself, but it still occurs. What could I add to this code to gain access to these (and other) folders?
You are trying to read from directory via the method intended to read from a file:
string s = Path.GetDirectoryName(ofd.FileName);
E_model = File.ReadAllBytes(s);
Replace it with:
E_model = File.ReadAllBytes(ofd.FileName);
You can't ready the directory, you have to read a file:
string s = Path.GetDirectoryName(ofd.FileName);
E_model = File.ReadAllBytes(s);
Try adding the file name here