簡體   English   中英

在vb.net中使用打開文件和保存文件對話框

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

用戶通過“打開文件”對話框選擇文件后,如何處理此操作? 例如,如果用戶選擇了一個.txt文件並打開了該文件,那么如何從該文件中獲取數據? 如何返回用戶在其中找到文件的路徑? 那么,如何保存文件?

我知道有一個OpenFileDialog.OpenFile()方法,但是我也很確定這不是我想要的。 我也嘗試了ToObject方法,但是我可能以某種方式弄亂了。

例如,是否有快速簡便的方法來打開圖像?

謝謝您的幫助!

順便說一下,這是在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)

您應該在處理IO的所有操作周圍放置Try ... Catch塊,否則將無法防止所有異常。

這是一個很好的示例: https : //web.archive.org/web/1/http : //blogs.techrepublic%2ecom%2ecom/programming-and-development/?p=481

這是一個瑣碎的問題,谷歌可以在幾秒鍾內回答。

您要處理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