3

我已经查看了MSDN 示例,但我仍然遇到问题。

我创建了一个超级简单的程序来将两个数字相乘,并在文本框中显示输出。现在我需要能够读取该文本框的值并将该值放入文本文件中,当单击“保存到文件”按钮时会弹出保存到文件对话框。

Private Sub MutiplyBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MutiplyBtn.Click
    Dim FirstNum As Double = Num1.Text
    Dim SecondNum As Double = Num2.Text
    Dim Answer2 As Double = FirstNum * SecondNum
    Answerbox.Text = Answer2
End Sub

Private Sub SaveResultToFile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveResultToFile.Click
    Dim myStream As Stream
    Dim saveFileDialog1 As New SaveFileDialog()

    saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
    saveFileDialog1.FilterIndex = 2
    saveFileDialog1.RestoreDirectory = True

    If saveFileDialog1.ShowDialog() = DialogResult.OK Then
        myStream = saveFileDialog1.OpenFile()
        If (myStream IsNot Nothing) Then
            System.IO.File.WriteAllText(Answerbox.Text)
            myStream.Close()
        End If
    End If
End Sub

目前,Visual Studio 给我一个错误:Overload resolution failed because no accessible 'WriteAllText' accepts this number of arguments.

4

2 回答 2

4

WriteAllText静态方法需要写入数据的文件的名称。
您可以直接使用在 saveFileDialog1 中选择的名称

If saveFileDialog1.ShowDialog() = DialogResult.OK Then
    System.IO.File.WriteAllText(saveFiledialog1.FileName, Answerbox.Text)
End If

相反,如果你真的想使用 OpenFile() 方法打开的流,你的代码应该是

   If saveFileDialog1.ShowDialog() = DialogResult.OK Then
        Dim sw As StreamWriter = new StreamWriter(saveFileDialog1.OpenFile())
        If (sw IsNot Nothing) Then 
            sw.WriteLine(Answerbox.Text)
            sw.Close()
        End If 
    End If 

代码是一个例子,需要加一点错误处理

于 2013-03-14T21:39:02.347 回答
1

嗨,我尝试了上述方法,但我以这种方式成功....

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
   SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
      If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK _
      Then
         My.Computer.FileSystem.WriteAllText _
         (SaveFileDialog1.FileName, RichTextBox1.Text, True)
      End If
End Sub
于 2013-12-24T10:06:05.073 回答