Open, Edit and Save Text File

tg93

Member
Joined
Jul 26, 2014
Messages
7
Programming Experience
Beginner
Hello, I am a beginner in VB and programming in general and have been reading many forums that have not helped very much. Here is my problem:

I have a text file (C:\Documents and Settings\Walid\Desktop\September\200009\20000917.t xt) that looks like this:

Time,DET#,VOL,OCC,Date 2000 09 17,
00:00:00,2,3,4,
6:00:00,200,32,42,
9:00:00,2,3,4,
...

I would like to change the top line to: Time,DET#,VOL,OCC,Date of:,Type,

and I would like to change all the other lines to:

00:00:00,2,3,4, 2000 09 17,c,
6:00:00,200,32,42, 2000 09 17,c,
9:00:00,2,3,4, 2000 09 17,c,
...

There are many other similar text files but I can figure out how to loop it myself. I am new at VB, so if you could keep your code simple and comment that would be much appreciated.
 
I have managed to solve the problem, thanks anyways

It's considered good form to post your solution so that it might help others with similar issues in future.
 
Here is my code, I have completed it by reading each line as a string (I would've liked to have been able to do it in some sort of comma delimited fashion for future knowledge but I was unable to figure it out). Main things to look at in code are:

1) Reader = File.OpenText("C:\Documents and Settings\Walid\Desktop\September\" _ & Trim(YearMonthv) & "\c" & Trim(CurrentDate) & ".txt")

2) The do loop, reading and editing the text file line by line

3) Writer = My.Computer.FileSystem. _OpenTextFileWriter(SaveTo, True)
Writer.WriteLine(arrayt)
Writer.Close()

VB.NET:
Imports System.IO
Imports System.Text
Public Class Form1


    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim watch As Stopwatch = Stopwatch.StartNew()   'Starts stopwatch
        Dim Reader As System.IO.StreamReader            'Declares the Reader
        Dim Writer As System.IO.StreamWriter            'Declares the Writer
        Dim i As Date                                   'Loop counter (by date)
        Dim j As Integer                                'Loop counter
        Dim k As Integer                                'Files notFound counter
        Dim StartDate As Date                           'Date to begin compiling text files
        Dim EndDate As Date                             'Date to stop compiling text files
        Dim SaveTo As String                            'Name of the file that will be saved
        Dim Yearv As String                             'Year value
        Dim Monthv1 As Integer                          'Month value (integer)
        Dim Monthv As String                            'Month value (string)
        Dim Dayv1 As Integer                            'Day value (integer)
        Dim Dayv As String                              'Day value (string)
        Dim DayofWeek As String                         'Weekday value
        Dim YearMonthv As String                        'Year and Month value (string)
        Dim CurrentDate As String                       'Date of the file being worked on (string)
        Dim line As String                              'Holds individual lines from the Reader
        Dim found As Boolean                            'Marks instances when a file does not exist
        Dim arrayf As New StringBuilder                 'Holds text to be printed in Files Not Found
        Dim arrayt As New StringBuilder                 'Holds text from text files


        TextBox1.Clear()                                'Clears textboxes
        notFound.Clear()


        Try
            StartDate = "#" & txtStartDate.Text & "#"   'User enters start & end date in textboxes
            EndDate = "#" & txtEndDate.Text & "#"
        Catch                                           'Catches invalid dates and exits with message
            MsgBox("Date(s) not valid.")
            Exit Sub
        End Try


        If StartDate > EndDate Then                     'Catches unordered dates and exits with message
            MsgBox("Start date cannot be after end date.")
            Exit Sub
        End If


        i = StartDate                               'Hold StartDate for counting
        j = 0                                       'Intializes loop counter
        k = 0                                       'Intialize number of times a file hasn't been found
        found = True                                'File is assumed to exist unless not found


        While (i <= EndDate)                        'Loop runs from start date to end date


            j = j + 1                               'Count loops
            Yearv = Str(i.Year)                     'Assigning Year, Month, Day, and Day of Week to different elements
            Monthv1 = i.Month
            Dayv1 = i.Day
            DayofWeek = WeekdayName(Weekday(i))


            If Monthv1 < 10 Then                                'Converts 1 to 01 for Month no. (due to naming convention of the files)
                Monthv = "0" + Trim(Str(Monthv1))
                YearMonthv = Yearv + Monthv                     'Corrects YearMonthv accordingly
            Else
                Monthv = Trim(Str(Monthv1))
                YearMonthv = Trim(Trim(Yearv) + Trim(Monthv))
            End If


            If Dayv1 < 10 Then                                      'Converts 1 to 01 for Day no. (due to naming convention of the files)
                Dayv = "0" + Trim(Str(Dayv1))
            Else
                Dayv = Str(Dayv1)
            End If


            CurrentDate = Trim(Yearv) + Trim(Monthv) + Trim(Dayv)   'Sets current date as string (due to naming convention of the files)


            SaveTo = "C:\Documents and Settings\Walid\Desktop\September\" _
                & Trim(YearMonthv) & "\a" & Trim(CurrentDate) & ".txt"                          'Name of file to be saved


            Try                                                                                 'Checking if file to be opened exists
                Reader = File.OpenText("C:\Documents and Settings\Walid\Desktop\September\" _
                            & Trim(YearMonthv) & "\c" & Trim(CurrentDate) & ".txt")             'Name of file to be opened
            Catch
                arrayf.AppendLine(SaveTo)                               'Saves the name of the file not found
                k = k + 1                                               'Counts number of files not found
                found = False                                           'Current date has no associated file
            End Try


            If found = True Then                                        'Reads only if file exists
                Do Until Reader.EndOfStream                             'Reads through the open file line by line to last line
                    line = Reader.ReadLine                              'Holds individual line for the iteration


                    If line.Contains("VOL") Then                        'Looks for the header
                        line = "Time,DET#,VOL,OCC,Date of:,Day,Type,"   'Modifies the header
                    Else
                        line = line + Trim(Yearv) + " " + Trim(Monthv) + " " _
                            + Trim(Dayv) + "," + Trim(DayofWeek) + ",c"             'Adds info to all other lines
                    End If
                    arrayt.AppendLine(line)                                         'Assigns the current line to the textbox
                Loop                                                                'Reiterate
                Reader.Close()                                                      'Closes the reader
            End If


            If found = True Then                        'Only saves files whose read files exists
                Writer = My.Computer.FileSystem. _
                OpenTextFileWriter(SaveTo, True)        'Opens text document
                Writer.WriteLine(arrayt)                'Writes the text saved to arrayt
                Writer.Close()                          'Closes the Writer
            End If
            arrayt.Clear()                              'Clears arrayt
            found = True                                'Reintialized as true


            i = i.AddDays(1)                            'Increments date by one day


        End While


        If k = 0 Then
            arrayf.AppendLine("All files present.")     'If all files are present
        End If
        notFound.Text = arrayf.ToString


        watch.Stop()                                                    'Stops stopwatch


        TextBox1.Text = "Program Complete. A total of " & (j - k) & _
            " text files compiled." & vbCrLf & k & _
            " files were not found or written." & vbCrLf & _
            "Program took " & Str(watch.Elapsed.TotalSeconds) & _
            " seconds to run."                                           'Output text


    End Sub
 
Back
Top