我已经查看了MSDN Example,但我仍然遇到问题。
我创建了一个超级简单的程序来乘以两个数字,并在文本框中显示输出。现在我需要能够读取该文本框值并将该值放入文本文件中,在单击“保存到文件”按钮时显示保存到文件对话框。
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.
答案 0 :(得分: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
代码是一个例子,你需要添加一些错误处理
答案 1 :(得分: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