0

我有这个代码

  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

如您所见,它不是每行放置一个输出,而是重复输出多次,然后对下一个输出执行相同操作...请帮助

4

1 回答 1

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
于 2013-10-26T16:46:08.737 回答