How do I make my application store the last path opened in openFileDialog and after new opening restore it?
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
acc_path = openFileDialog1.FileName;
Settings.Default.acc_path = acc_path;
foreach (string s in File.ReadAllLines(openFileDialog1.FileName))
{
accs.Enqueue(s);
}
label2.Text = accs.Count.ToString();
}
This is the easiest way: FileDialog.RestoreDirectory.
After changing Settings you have to call
Settings.Default.Save();
and before you open the OpenFileDialog you set
openFileDialog1.InitialDirectory = Settings.Default.acc_path;
I think it would be enough for you to use SetCurrentDirectory to ste the current directory for the OS. So on the next dialog opening it would pick that path.
Or simply save path into some variable of your application and use
FileDialog.InitialDirectory property.
The following is all you need to make sure that OpenFileDialog will open at the directory the user last selected, during the lifetime off your application.
OpenFileDialog OpenFile = new OpenFileDialog();
OpenFile.RestoreDirectory = false;
I find that all you have to do is NOT set the initial directory and the dialog box remembers your last save/open location. This remembers even after the application is closed and reopened. Try this code with the initial directory commented out. Many of the suggestions above will also work but if you are not looking for additional functionality this is all you have to do.
private void button1_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
//openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
I know this is a bit of an old thread, but I was not able to find a solution I liked to this same question so I developed my own. I did this in WPF but it should work almost the same in Winforms.
Essentially, I use an app.config file to store my programs last path.
When my program starts I read the config file and save to a global variable. Below is a class and function I call when my program starts.
public static class Statics
{
public static string CurrentBrowsePath { get; set; }
public static void initialization()
{
ConfigurationManager.RefreshSection("appSettings");
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
CurrentBrowsePath = ConfigurationManager.AppSettings["lastfolder"];
}
}
Next I have a button that opens the file browse dialog and sets the InitialDirectory property to what was stored in the config file. Hope this helps any one googling.
private void browse_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog open_files_dialog = new OpenFileDialog();
open_files_dialog.Multiselect = true;
open_files_dialog.Filter = "Image files|*.jpg;*.jpeg;*.png";
open_files_dialog.InitialDirectory = Statics.CurrentBrowsePath;
try
{
bool? dialog_result = open_files_dialog.ShowDialog();
if (dialog_result.HasValue && dialog_result.Value)
{
string[] Selected_Files = open_files_dialog.FileNames;
if (Selected_Files.Length > 0)
{
ConfigWriter.Update("lastfolder", System.IO.Path.GetDirectoryName(Selected_Files[0]));
}
// Place code here to do what you want to do with the selected files.
}
}
catch (Exception Ex)
{
MessageBox.Show("File Browse Error: " + Environment.NewLine + Convert.ToString(Ex));
}
}
You can use the InitialDirectory property : http://msdn.microsoft.com/fr-fr/library/system.windows.forms.filedialog.initialdirectory.aspx
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.InitialDirectory = previousPath;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
previousPath = Path.GetDirectoryName(openFileDialog1.FileName);
acc_path = openFileDialog1.FileName;
Settings.Default.acc_path = acc_path;
foreach (string s in File.ReadAllLines(openFileDialog1.FileName))
{
accs.Enqueue(s);
}
label2.Text = accs.Count.ToString();
}
if your using
Dim myFileDlog As New OpenFileDialog()
then you can use this to restore the last directory
myFileDlog.RestoreDirectory = True
and this to not
myFileDlog.RestoreDirectory = False
(in VB.NET)
Related
I am trying to open a file by pressing a button (a label to be more exact but it works just the same way)
For some reason when the FileDialog opens and I select the file and press open it doesnt open the file it only closes the FileDialog
private void selectLbl_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = "c:\\";
ofd.Filter = "Script files (*.au3)|*.au3";
ofd.RestoreDirectory = true;
ofd.Title = ("Select Your Helping Script");
if (ofd.ShowDialog() == DialogResult.OK)
{
ofd.OpenFile(); //Not sure if there is supposed to be more here
}
}
ofd.OpenFile();
is returning the content of the file as Stream of bytes like described here. If you want to open the file like you described it, use
if (ofd.ShowDialog() == DialogResult.OK)
{
System.Diagnostics.Process.Start(ofd.FileName);
}
So your selected file starts with the associated application.
ofd.OpenFile() opens the file selected by the user as a Stream that you can use to read from the file.
What you do with that stream depends on what you are trying to achieve. For example, you can read and output all lines:
if (ofd.ShowDialog() == DialogResult.OK)
{
using (TextReader reader = new StreamReader(ofd.OpenFile()))
{
string line;
while((line = t.ReadLine()) != null)
Console.WriteLine(line);
}
}
Or if it is an xml file you can parse it as xml:
if (ofd.ShowDialog() == DialogResult.OK)
{
using(XmlTextReader t = new XmlTextReader(ofd.OpenFile()))
{
while (t.Read())
Console.WriteLine($"{t.Name}: {t.Value}");
}
}
The OpenFileDialog is not a dialog that opens the file. It only communicates with the operator with a dialog that is commonly shown if a program needs to know what file to open. So it is only a dialog box, not a file opener.
You decide what to do if the user pressed ok or cancel:
private void selectLbl_click(object sender, ...)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.InitialDirectory = "c:\\";
ofd.Filter = "Script files (*.au3)|*.au3";
ofd.RestoreDirectory = true;
ofd.Title = ("Select Your Helping Script");
var dlgResult = ofd.ShowDialog(this);
if (dlgResult == DialogResult.OK)
{ // operator pressed OK, get the filename:
string fullFileName = ofd.FileName;
ProcessFile(fullFileName);
}
}
}
if (ofd.ShowDialog() == DialogResult.OK)
{
ofd.OpenFile(); //Not sure if there is supposed to be more here
}
In my chat program I need to send file to other users but I have problem.
When I trying to send my file visual studio give me an exception the given path's format is not supported;
private void button3_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "A:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer).ToString();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
byte[] bytes = File.ReadAllBytes(openFileDialog1.ToString());
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error:"+ ex.Message);
}
}
}
Please help.
Try File.ReadAllBytes(openFileDialog1.FileName);.
You're using openFileDialog1.ToString(), which will return something like "System.Windows.Forms.OpenFileDialog", not the path of the selected file.
Whenever I try to open a custom file to a textbox or something which will display code. it never works, I'm not sure what I am doing wrong.
I want my program to display what is inside the file when I open it, I have this below:
private void button1_Click(object sender, EventArgs e)
{
//Show Dialogue and get result
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "rbt files (*.rbt)|*.rbt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
File.WriteAllText("", CodeBox.Text);
}
}
}
catch (Exception ex)
{
MessageBox.Show("RBT7 file open");
}
}
}
It only displays the RBT7 in a messagebox which is not what I want, I want the file to open and display its information to some sort of textbox which displays code.
Please read the documentation for File.WriteAllText.
The first parameter:
path: The file to write to.
You're passing it "". That is not a path. Are you trying to write all the text from the file into CodeBox.Text or write all the text from CodeBox.Text into a file?
In your comment, you indicate the former. Try this:
string[] lines = System.IO.File.ReadAllLines(#"your file path");
foreach (string line in lines)
{
CodeBox.Text += line;
}
You haven't shown the code for CodeBox so I can't guarantee the results of this.
Try this:
Replace this code
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
File.WriteAllText("", CodeBox.Text);
}
}
with this
{
CodeBox.Text = File.ReadAllText(openFileDialog1.FileName);
}
I am able to open a file dialog, now i want to know how do i get the path of the file in var variable something like
OpenFileDialog fd1 = new OpenFileDialog();
fd1.InitialDirectory = "c:\\";
fd1.Filter = "pdf files (*.pdf)|*.pdf|All Files (*.*)|*.*";
fd1.FilterIndex = 2;
fd1.RestoreDirectory = true;
so i want in my var something like
var path = #"c:\abc.pdf";
Is it possible
Here it is:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var path = openFileDialog1.FileName;
}
This way you'll get your path to file like:
C:\folder1\folder2\fffffffff...\abc.pdf
Update:
you'll change your "var" into "string" and you'll make your path variable a global variable. here is an example:
private string path;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
path = openFileDialog1.FileName;
}
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(path);
}
you don't need to make your variable a public because you are in the same class!!!
Update:
Think that this will do
AxAcroPDF1.src = path;
The Process.Start should launch a new process to open the pdf file with default client that is Adobe Reader.
You can prompt user with filedialog to get you a file path.
If you want to get some of specific folders you can try
String PersonalFolder =
Environment.GetFolderPath(Environment.SpecialFolder.Personal);
Environment have alot of folders that are specific for machine.
hope it helps
Does anyone know any articles or sites showing how to create a "Save as" dialogue box in win forms. I have a button, user clicks and serializes some data, the user than specifies where they want it saved using this Save as box.
You mean like SaveFileDialog?
From the MSDN sample, slightly amended:
using (SaveFileDialog dialog = new SaveFileDialog())
{
dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
dialog.FilterIndex = 2 ;
dialog.RestoreDirectory = true ;
if (dialog.ShowDialog() == DialogResult.OK)
{
// Can use dialog.FileName
using (Stream stream = dialog.OpenFile())
{
// Save data
}
}
}
Use the SaveFileDialog control/class.
Im doing a notepad application in c# i came over this scenario to save file as try this out.It will work perfectly
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(saveFileDialog1.FileName.ToString());
file.WriteLine(richTextBox1.Text);
file.Close();
}
}