OpenFileDialog and SaveFileDialog

T

Tony Johansson

Hello!

The object called dlgOpenFile is of type OpenFileDialog.

In this example the eventhandler OnFileOpen is called when the Open File in
a menu is clicked.
Here we call the OpenFileDialog and select a filename to be opened and then
if the Open
button is selected we call the OpenFile method.

Now to my question: I just wonder when is the file opened. Is it at the same
time as
the static method File.ReadAllText(filename);
is called
or
is it automatically done in the OpenFileDialog?


private void OnFileOpen(object sender, EventArgs e)
{
if (dlgOpenFile.ShowDialog() == DialogResult.OK)
{
filename = dlgOpenFile.FileName;
OpenFile();
}
}

protected void OpenFile()
{
try
{
textBoxEdit.Clear();
textBoxEdit.Text = File.ReadAllText(filename);
}
catch(IOException ex)
{
MessageBox.Show(ex.Message, "Simple Editor",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}

//Tony
 
C

Ciaran O''Donnell

Thats correct. That functions opens the file, reads all the text from it and
closes it again. The OpenFileDialog just returns a file name to you by
default and doesnt open the file. It does have functions on it to Open the
file and return a stream but that would mean you would have to write the code
to read the contents of the file.
 
F

Family Tree Mike

Neither OpenFileDialog, nor SaveFileDialog actually open a file. The
filename returned is for you to use in code after opening. ReadAllText will
open and close the file as part of its code.
 
M

Michael Huber

Hello Tony,

it is opend while during executing File.ReadAllText(filename);

The FileOpenDialog only returns the Filename (as string) of the
selected file an thus does not open it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top