简体   繁体   English

在vb.net中使用打开文件和保存文件对话框

[英]Using the open file and save file dialogs in vb.net

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? 例如,如果用户选择了一个.txt文件并打开了该文件,那么如何从该文件中获取数据? 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. 我知道有一个OpenFileDialog.OpenFile()方法,但是我也很确定这不是我想要的。 I have also tried the ToObject method, but I probably messed up somehow. 我也尝试了ToObject方法,但是我可能以某种方式弄乱了。

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. 顺便说一下,这是在VB.net中。

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. 您应该在处理IO的所有操作周围放置Try ... Catch块,否则将无法防止所有异常。

Here is some good example: https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/programming-and-development/?p=481 . 这是一个很好的示例: https : //web.archive.org/web/1/http : //blogs.techrepublic%2ecom%2ecom/programming-and-development/?p=481

This is a trivial question that could be answered by Google in a matter of seconds. 这是一个琐碎的问题,谷歌可以在几秒钟内回答。

You want to handle the FileOk event: 您要处理FileOk事件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM