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.
Related
Good day.
I have a Windows forms application (C#).
With the "open file dialog" I can select a .pdf file.
Selected .pdf file is copied and stored in a pre-determined destination.
File path of selected .pdf file is stored in an SQL database.
What is the function/method to open a .pdf file (in axAcroPDF...), which is stored in a folder and its file path is stored in a database?
This is what I have, code vise:
private void txtST1Cap_DoubleClick(object sender, EventArgs e)
{
SavedDocumentPath1 = #"XXX\";
using (OpenFileDialog OpenFileDialog1 = new OpenFileDialog() { ValidateNames = true, Multiselect = false, Filter = "PDF|*.pdf" })
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//display PDF in reader
OpenedDocument1 = openFileDialog1.FileName;
axAcroPDF1ST1.src = openFileDialog1.FileName;
//code for getting REF No. from opened file name
OpenedDocumentREF = Path.GetFileName(openFileDialog1.FileName);
REFfromOpenedDocument = OpenedDocumentREF.Substring(0, 12);
txtST1Cap.Text = REFfromOpenedDocument;
//destination of to-be saved document
SavedDocLoc1 = (SavedDocumentPath1 + Path.GetFileName(openFileDialog1.FileName));
lblST1CapLocation.Text = SavedDocLoc1;
}
}
private void btnST1Cap_Click(object sender, EventArgs e)
{
openFileDialog1.FileName=SavedDocLoc1;
axAcroPDF1ST1.src = openFileDialog1.FileName;
}
Button Clicl btnST1Cap does not work.
Thank you.
I was almost correct.
So, if one wants to open a PDF document in a "default program" System.Diagnostics.Process,... is used:
private void btnST1Cap_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start(lblST1CapLocation.Text);
}
As mentioned, this opens a default .pdf browser.
I wanted, to open it in my form (in axAcroPDF...):
private void btnST1Cap_Click(object sender, EventArgs e)
{
axAcroPDF1ST1.src = lblST1CapLocation.Text;
}
Yaaaay 4 ME!
In above cases "lblST1CapLocation.Text" is the label where file path is stored.
Direct file path can be inserted if wished:
System.Diagnostics.Process.Start(#"c:\myPdf.pdf");
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 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 have a problem. I have created a temporary .csv file, which contains a lot of data. The directory is a string: path = #"C:\Users\xxxxx\Documents\TempFile.csv";.
I want to save this temporary file as a .csv file, when the user click on the save button. I have created a dialog, so the user is able to choose where to save the file.
private void SaveBT_Click_1(object sender, EventArgs e)
{
{
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "CSV File|*.csv";
saveDialog.Title = "Gem en CSV fil";
if (saveDialog.ShowDialog() == DialogResult.OK)
{
}
}
}
erm, how about?
File.Copy(tempFileName, saveFialog.FileName);
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