【问题标题】:Using the open file and save file dialogs in vb.net在 vb.net 中使用打开文件和保存文件对话框
【发布时间】:2009-09-06 03:12:30
【问题描述】:

一旦用户通过打开文件对话框选择了一个文件,我该如何处理这个操作?例如,如果用户选择了一个 .txt 文件并打开了它,它如何从文件中获取数据?它如何返回用户找到文件的路径?那么,如何保存文件呢?

我知道有一个 OpenFileDialog.OpenFile() 方法,但我也很确定这不是我想要的。我也尝试过 ToObject 方法,但我可能不知何故搞砸了。

例如,有没有一种快速简便的方法来打开图像?

感谢您的帮助!

顺便说一句,这是在 VB.net 中。

【问题讨论】:

    标签: vb.net .net


    【解决方案1】:
    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 块,你将无法阻止所有异常。

    【讨论】:

    • 对,有道理。现在,您所做的只是将文件名更改为另一个文件名,我如何在位图中实际捕获文件本身?
    • 如何在位图中捕获文件本身???我不知道那是什么意思。您是否尝试打开图像文件?您是否尝试在窗口中显示图像文件?我没有更改文件的名称,也没有涉及“其他文件”。在我看来,我们现在的情况是无法沟通。
    • 哦,等等,我看到了我的问题。没关系,效果很好,谢谢!现在我只需要保存。
    【解决方案2】:

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

    这是一个微不足道的问题,Google 可以在几秒钟内回答。

    【讨论】:

      【解决方案3】:

      你想处理 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-02-07
        • 1970-01-01
        • 1970-01-01
        • 2021-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多