Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 443
  • Last Modified:

C# text file manipulation help

Environment: C#

Begin
1600016089875 031
1600016089883 125
1600016089875 033
1600016089875 033
1600016089875 034
1600016089875 036
1600016089875 037
1600016089875 038
1600016089875 039
1600016089875 021
1600016089875 024
End

I am creating a txt file with some rows between Begin and End and its working fine. Now, I would like to split the records so that there are a maximum of only 3 rows between each Begin-End block within the same file.

The output for temp.txt should look something like below:


Begin
1600016089875 031
1600016089883 125
1600016089875 033
End

Begin
1600016089875 033
1600016089875 034
1600016089875 036
End

Begin
1600016089875 037
1600016089875 038
1600016089875 039
End

Begin
1600016089875 021
1600016089875 024
End


Please advise, what would be an easy and efficient method to achieve this?

Thanks.
0
Ricky66
Asked:
Ricky66
1 Solution
 
YZlatCommented:
try something like that:

 Dim fulltext As String
        Dim sr As StreamReader = Nothing
        Dim arrRows() As String
        Dim path As String = "C:\Test\test.txt"
        Dim i As Integer

        If (File.Exists(path)) Then
            sr = New StreamReader(path)
            fulltext = sr.ReadToEnd
            arrRows = Split(fulltext, vbCrLf)
        End If
        sr.Close()

        Dim fs As FileStream = New FileStream(path, FileMode.Open)
        Dim sw As StreamWriter = New StreamWriter(fs)


        i = 1
        While i <= arrRows.Length - 2   
            If ((i + 3) <= arrRows.Length - 2) Then
                sw.WriteLine("Begin")
                sw.WriteLine(arrRows(i))
                sw.WriteLine(arrRows(i + 1))
                sw.WriteLine(arrRows(i + 2))
                sw.WriteLine("End")
                i = i + 3
            Else
                sw.WriteLine("Begin")
                While (i <= arrRows.Length - 2)


                    sw.WriteLine(arrRows(i))
                    i = i + 1
                End While
                sw.WriteLine("End")
            End If

        End While

        sw.Flush()
        sw.Close()
        fs.Close()

Open in new window

0
 
Ricky66Author Commented:
Thanks!
0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now