我做了一些谷歌搜索,每个人都给了我相同的答案,但没有工作。我希望它缺少一些简单的东西。我正在尝试测试一行到txt文件。当我使用类似的代码时,文件创建得很好,并且没有抛出任何错误,txt只是没有写入/保存到文件中。我在VB中使用流编写器。 这是我的代码:
Imports System.IO
Public Class Form1
Private Sub btnGen2DArray_Click(sender As Object, e As EventArgs)
Handles btnGen2DArray.Click
Try
'this is the file created and where it is saved:
Dim fileLoc As String = "c:\Users\clint\save.txt"
If File.Exists(fileLoc) Then
Using sw As New StreamWriter(fileLoc)
sw.Write("Test line write")
sw.Close()
End Using
End If
MsgBox("C++ 2D array text file created in: " + fileLoc, MsgBoxStyle.OkOnly, "Successful")
Catch ex As Exception
MsgBox("error: " + e.ToString(), MsgBoxStyle.OkOnly, "Error")
End Try
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
Close()
End Sub
End Class
如果这有帮助,我正在使用vb 2012。普通窗口形成应用程序
答案 0 :(得分:3)
完成后你需要close your StreamWriter。 sw.Close
您必须调用Close以确保正确写出所有数据 到底层流。
更好的是,使用Using。以下内容将进入你的if:
Using sw As New StreamWriter(fileLoc)
sw.Write("Test line write")
For rowcount As Double = 1 To rows
For colcount As Double = 1 To cols
'when the file write test works I will finish the rest of the code here
Next
Next
End Using
这将自动为您处理StreamWriter。