views:

464

answers:

3

Once a user has selected a file with the open file dialog, how can I handle this action? For example, if the user has selected a .txt file and has opened it, how can it get the data from the file? How can it return the path that the user found the file in? Then, how can it save the file?

I know that there is a OpenFileDialog.OpenFile() method, but I am also pretty sure this is not what I am looking for. I have also tried the ToObject method, but I probably messed up somehow.

Is there a quick and easy way to open an image, for example?

Thanks for the help!

This is in VB.net by the way.

+3  A: 
Dim dlg_open As New OpenFileDialog()
If (dlg_open.Show() <> DialogResult.OK) Then Return

'if a textfile, then
Dim content As String() = IO.File.ReadAllLines(dlg_open.FileName)

'if an image, then
Dim img As New Bitmap(dlg_open.FileName)

You should put Try...Catch blocks around all operations dealing with IO, you will not be able to prevent all exceptions.

David Rutten
Right, makes sense. Now, all your line there does though is change the name of the file to the other file name, how do I actually capture the file itself in the bitmap?
Cyclone
How do you capture the file itself in a bitmap??? I have no idea what that means. Are you trying to open an image file? Are you trying to display an image file in a window?I'm not changing the name of the file, and there is no "other file" involved.It seems to me, what we have here, is a failure to communicate.
David Rutten
Oh wait, i see my issue. Nevermind, it works great, and thanks! Now all I need is saving.
Cyclone
+3  A: 

Here is some good example: http://blogs.techrepublic.com.com/programming-and-development/?p=481.

This is a trivial question that could be answered by Google in a matter of seconds.

Eran Betzalel
Agreed.
Charlie Salts
A: 

You want to handle the FileOk event:

Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
    Dim path As String = OpenFileDialog1.FileName

    If fileIsBitmap Then
        ' say the file is a bitmap image '
        Dim bmp As New Bitmap(path)

        ' rotate the image 90 degrees '
        bmp.RotateFlip(RotateFlipType.Rotate90FlipNone)

        ' save the image '
        bmp.Save(path)

    ElseIf fileIsTextFile Then
        ' or say the file is a text file '
        Dim fs As New IO.FileStream(path, IO.FileMode.Append)
        Dim sr As New IO.StreamWriter(fs)

        ' write a new line at the end of the file '
        sr.WriteLine("This is a new line.")

        ' close the FileStream (this saves the file) '
        sr.Close()
        fs.Close()
    End If
End Sub
Dan Tao