datatheoz

Randomize File Lines 100%

Sep 13th, 2020
1,536
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 2.21 KB | None | 0 0
  1.     Private Shared ReadOnly Rnd As New Random(Now.Millisecond)
  2.  
  3.     Public Shared Sub RandomizeLines(targetFile As String, Optional randomizeRate As Integer = 10, Optional keepFile As Boolean = False)
  4.         randomizeRate = Math.Max(randomizeRate, 2)
  5.  
  6.         Dim currPath As String = Path.GetDirectoryName(targetFile)
  7.         Dim currFile As String = Path.Combine(currPath, Path.GetFileNameWithoutExtension(targetFile) & " (Randomized)" & Path.GetExtension(targetFile))
  8.         Dim currWriter As String
  9.  
  10.         Dim writers() As StreamWriter = {}
  11.         Array.Resize(writers, randomizeRate)
  12.         For i As Integer = 0 To randomizeRate - 1
  13.             writers(i) = New StreamWriter(Path.Combine(currPath, "temp" & i.ToString & ".txt")) 'With {.AutoFlush = True}
  14.         Next
  15.  
  16.         Dim o As Integer
  17.         Dim lastIndex As Integer
  18.         Using fs As FileStream = File.OpenRead(targetFile)
  19.             Using sr As New StreamReader(fs)
  20.                 While Not sr.EndOfStream
  21.                     o = Rnd.Next(randomizeRate)
  22.                     While o = lastIndex
  23.                         o = Rnd.Next(randomizeRate)
  24.                         If o = lastIndex Then
  25.                             o = Math.Min(o + 1, randomizeRate - 1)
  26.                         End If
  27.                     End While
  28.                     lastIndex = o
  29.  
  30.                     writers(o).WriteLine(sr.ReadLine())
  31.                 End While
  32.             End Using
  33.         End Using
  34.  
  35.         Using sw As New StreamWriter(currFile) 'With {.AutoFlush = True}
  36.             For i As Integer = 0 To randomizeRate - 1
  37.                 writers(i).Dispose()
  38.                 currWriter = Path.Combine(currPath, "temp" & i.ToString & ".txt")
  39.                 Using reader As New StreamReader(currWriter)
  40.                     While Not reader.EndOfStream
  41.                         sw.WriteLine(reader.ReadLine)
  42.                     End While
  43.                 End Using
  44.                 File.Delete(currWriter)
  45.             Next
  46.         End Using
  47.  
  48.         If keepFile Then
  49.             Try
  50.                 File.Delete(targetFile)
  51.                 Rename(currFile, targetFile)
  52.             Catch ex As Exception
  53.  
  54.             End Try
  55.         End If
  56.     End Sub
Advertisement