StreamWriter中不需要的重复

时间:2013-10-26 16:39:24

标签: vb.net

我有这段代码

  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

它的作用是创建20个随机句子,并在第3行中声明“Validchars”,然后将输出写入带有附加功能的文本文件中。我想每行写一个输出,例如:

4926022cabea67acc9c95035ff6ec492
7ca00313c590f990fa797c73ec1d3305
303a7364c220f3d02c5df8b5b39e00ae

但我得到的问题是它多次重复这些行,这是一个示例输出(我删除了一些行以使其更短):

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

正如你所看到的那样,它不是每行输出一个输出,而是多次重复输出,然后对下一个输出做同样的事情......请帮忙

1 个答案:

答案 0 :(得分:7)

从循环中删除随机

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