TAGS :Viewed: 8 - Published at: a few seconds ago

[ Unwanted repetition in StreamWriter ]

I have this code

  Dim sw As StreamWriter
    For x As Integer = 0 To 20
        Dim validchars As String = "cfeabd0123456789"

        Dim sb As New StringBuilder()
        Dim rand As New Random()
        For i As Integer = 1 To 32
            Dim idx As Integer = rand.Next(0, validchars.Length)
            Dim randomChar As Char = validchars(idx)
            sb.Append(randomChar)
        Next i

        Dim randomString = sb.ToString()
        sw = File.AppendText("C:\file.txt")
        sw.WriteLine(randomString)
        sw.Close()
    Next

What it does is creating 20 random sentences with the "Validchars" declared in the 3rd line and then it writes the output into a text file with appending feature . I want to write one output per line for example :

4926022cabea67acc9c95035ff6ec492
7ca00313c590f990fa797c73ec1d3305
303a7364c220f3d02c5df8b5b39e00ae

But the problem I get is that it repeats the lines many times , here's an example output (I have deleted some lines to make it shorter) :

4926022cabea67acc9c95035ff6ec492
4926022cabea67acc9c95035ff6ec492
4926022cabea67acc9c95035ff6ec492
4926022cabea67acc9c95035ff6ec492
4926022cabea67acc9c95035ff6ec492
4926022cabea67acc9c95035ff6ec492
4926022cabea67acc9c95035ff6ec492
4926022cabea67acc9c95035ff6ec492
c45a315faa856e1c681e7ddd5d2c1276
c45a315faa856e1c681e7ddd5d2c1276
c45a315faa856e1c681e7ddd5d2c1276
c45a315faa856e1c681e7ddd5d2c1276
c45a315faa856e1c681e7ddd5d2c1276
c45a315faa856e1c681e7ddd5d2c1276
c45a315faa856e1c681e7ddd5d2c1276
c45a315faa856e1c681e7ddd5d2c1276
c45a315faa856e1c681e7ddd5d2c1276
c45a315faa856e1c681e7ddd5d2c1276

As you can see instead of putting one output per line it repeats the output many times and then it does the same for the next output ... Please help

Answer 1


Remove the Random from the Loop

Sub GenerateRandomFileContent()
    Dim rand As New Random()
    Dim sw As StreamWriter
    For x As Integer = 0 To 20
        Dim validchars As String = "cfeabd0123456789"

        Dim sb As New StringBuilder()

        For i As Integer = 1 To 32
            Dim idx As Integer = rand.Next(0, validchars.Length)
            Dim randomChar As Char = validchars(idx)
            sb.Append(randomChar)
        Next i

        sb.Append(Environment.NewLine)  ' Remove this line if not needed

        ' Appends the Text to file
        Dim randomString = sb.ToString()
        sw = File.AppendText("C:\file.txt")
        sw.WriteLine(randomString)
        sw.Close()

        ' To Append this Text you could use just these lines below
        'Dim randomString = sb.ToString()
        'File.AppendAllText("C:\file.txt", randomString)
    Next
End Sub