How to open a file in C# using FileOpenDialog - c#

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
}

Related

Load a file then save without save dialog

Stream scriptelfen;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if((scriptelfen = openFileDialog1.OpenFile())!= null)
{
string strfilename = openFileDialog1.FileName;
string filetext = File.ReadAllText(strfilename);
script_box.Text = filetext;
When I opened my file, it is displaying text or hex code extension. I want to be able to push save file. I don't have to do a save file dialog is this possible at all ?
WriteAllText in MSDN
File.WriteAllText("C:\file.txt", "your content.");

display file instead of RSC version

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);
}

How to save last folder in openFileDialog?

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)

How do I show the name of the current open file in the Form title?

I'm making a text editor and I'd like to display the name of the current open file in the Form title (like Notepad does where it says "Untitled - Notepad" or " "File - Notepad").
I'm assuming this is done working with the SaveFileDialog and OpenFileDialog, so I'll post my current code.
OpenFile:
private void OpenFile()
{
NewFile();
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open File";
ofd.FileName = "";
ofd.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html";
if (ofd.ShowDialog() != DialogResult.OK) return;
StreamReader sr = null;
try
{
sr = new StreamReader(ofd.FileName);
this.Text = string.Format("{0} - Basic Word Processor", ofd.FileName);
richTextBoxPrintCtrl1.Text = ofd.FileName;
richTextBoxPrintCtrl1.Text = sr.ReadToEnd();
filepath = ofd.FileName;
richTextBoxPrintCtrl1.LoadFile(fileName, RichTextBoxStreamType.RichText);
}
catch
{
}
finally
{
if (sr != null) sr.Close();
}
SaveFile
private void SaveFileAs()
{
SaveFileDialog sfdSaveFile = new SaveFileDialog();
sfdSaveFile.Title = "Save File";
sfdSaveFile.FileName = "Untitled";
sfdSaveFile.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html";
if (sfdSaveFile.ShowDialog() == DialogResult.OK)
try
{
filepath = sfdSaveFile.FileName;
SaveFile();
this.Text = string.Format("{0} - Basic Word Processor", sfdSaveFile.FileName);
}
catch (Exception exc)
{
}
void SetWindowTitle(string fileName) {
this.Text = string.Format("{0} - Basic Text Editor", System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog.Filename));
How can I get the file name and put it in the Form's title (like Notepad does where it has the name of the file followed by the name of the text editor).
While opening . . .
private void OpenFile()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open File";
ofd.FileName = "";
ofd.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html";
ofd.ShowDialog();
try
{
// just one line is added
this.Text = string.Format("{0} - MyNotepad", Path.GetFileName(ofd.Filename));
richTextBoxPrintCtrl1.Text = ofd.FileName;
StreamReader stread = new StreamReader(richTextBoxPrintCtrl1.Text);
richTextBoxPrintCtrl1.Text = stread.ReadToEnd();
stread.Close();
richTextBoxPrintCtrl1.LoadFile(fileName, RichTextBoxStreamType.RichText);
}
catch { }
}
While saving . . .
private void SaveFileAs()
{
SaveFileDialog sfdSaveFile = new SaveFileDialog();
sfdSaveFile.Title = "Save File";
sfdSaveFile.FileName = "Untitled";
sfdSaveFile.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html";
if (sfdSaveFile.ShowDialog() == DialogResult.OK)
try
{
richTextBoxPrintCtrl1.SaveFile(sfdSaveFile.FileName, RichTextBoxStreamType.RichText);
filepath = sfdSaveFile.FileName;
// just one line is added
this.Text = string.Format("{0} - MyNotepad", Path.GetFileName(sfd.Filename));
}
catch (Exception exc)
{
}
}
Just an update
Toby- The empty catch blocks are needed. If the user cancels the ofd or sfd without the catch block, the program crashes. It keeps the program from crashing
You do not need the catch block to check if User selected OK / Cancel.
OpenFileDialog & SaveFileDialog has method ShowDialog that returns DialogResult
and value of DialogResult.OK tells that user has selected file to open / save and has not cancelled the operation.
And example with OpenFile
private void OpenFile()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open File";
ofd.FileName = "";
ofd.Filter = "Rich Text Files (.rtf)|.rtf|Text Document (.txt)|.txt|Microsoft Word Document (.doc)|.doc|Hypertext Markup Language Document (.html)|.html";
if (ofd.ShowDialog() == DialogResult.OK)
{
// just one line is added
this.Text = string.Format("{0} - MyNotepad", Path.GetFileName(ofd.Filename));
richTextBoxPrintCtrl1.Text = ofd.FileName;
StreamReader stread = new StreamReader(richTextBoxPrintCtrl1.Text);
richTextBoxPrintCtrl1.Text = stread.ReadToEnd();
stread.Close();
richTextBoxPrintCtrl1.LoadFile(fileName, RichTextBoxStreamType.RichText);
}
}
You can wrap it in a function like this:
void SetWindowTitle(string fileName) {
this.Text = string.Format("{0} - MyEditor", System.IO.Path.GetFileName(fileName));
}
..and pass in the dialog FileName..
EDIT:
Your issue is that you're not calling the function I gave you. You have the function I gave you above.. but you don't call it.
Replace this:
this.Text = string.Format("{0} - Basic Word Processor", sfdSaveFile.FileName);
With this:
SetWindowTitle(sfdSaveFile.FileName);
And replace this:
this.Text = string.Format("{0} - Basic Word Processor", ofd.FileName);
With this:
SetWindowTitle(ofd.FileName);

Winforms Save as

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();
}
}

Categories

Resources