Вопрос

I did some google searching and everyone gives me the same answer which isn't working. I hope its something simple I am missing. I am trying to test write a line to a txt file. The file was created just fine when I used similar code, and no errors are thrown, the txt just doesn't write/save to the file. I am using stream writer in VB. Here is my code:

   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

I am using vb 2012 if this helps. Normal windows form application.

Это было полезно?

Решение

You need to close your StreamWriter when you are done. sw.Close

You must call Close to ensure that all data is correctly written out to the underlying stream.

Better yet, use Using. The following would go inside your 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

This will automatically dispose of the StreamWriter for you.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top