Question Reading from and Writing to text files

rituhooda

Member
Joined
Mar 10, 2010
Messages
13
Programming Experience
Beginner
Input File to read:
SAMPLE NO: 10S-02013
Moisture 10.1
DryMat 89.9
SAMPLE NO: 10S-02014
Moisture 10.1
DryMat 89.9

Output file should be

10S-02013|Moisture|10.1
10S-02013|DryMat|89.9
10S-02013|CrdPro|9.6
10S-02014|Moisture|10.1
10S-02014|DryMat|89.9
10S-02014|CrdPro|9.6
My program looks like this
VB.NET:
Private Sub Process_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Process.Click

    Dim textFileName As String = "C:\NIR\niroutput.txt"
    Dim textFile As IO.StreamWriter = IO.File.CreateText(textFileName) 'Final output file
    Dim readFileName As String = "C:\NIR\nir.dat" 'Raw result file
    Dim readFile As IO.StreamReader = IO.File.OpenText(readFileName)
    Dim sampleNo As String
    'Dim result As Decimal
    Dim finalSampleNo As String
    Dim testAndResult As String

    '  Dim sResults As String
    Try
        Do While (readFile.Peek <> -1)

            sampleNo = readFile.ReadLine()  'Stores value of Sample Number 
            finalSampleNo = Trim((Mid(sampleNo, 12)))

            testAndResult = readFile.ReadLine()
            Do
                If Mid(testAndResult, 1, 10) <> "SAMPLE NO:" Then
                    Dim ar As New ArrayList
                    ar.Add(finalSampleNo)

                    ar.Add(testAndResult)
                    Dim Str As String
                    Str = Join(ar.ToArray(), "|")
                    MsgBox(Str)

                    textFile.WriteLine(Str)
                    testAndResult = readFile.ReadLine()
                End If
            Loop Until (readFile.Peek <> -1)

        Loop
            '      Return textFileName

    Catch ex As Exception
        Throw
        '     Return ""
        MsgBox("Some Error")
    Finally
        If textFile IsNot Nothing Then
            textFile.Close()
            textFile = Nothing
        End If

        If readFile IsNot Nothing Then
            readFile.Close()
            readFile = Nothing
        End If
    End Try

End Sub
I am not getting the right output I need, as whenever it reads a line, it looses my sample numeber. Any help will be appreciated.Thanks
 
Last edited by a moderator:
Not seeing where you're getting your CrdPro data from. This works with your sample data minus the CrdPro line.

VB.NET:
Imports System.IO

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Using sr As New StreamReader("C:\Temp\unformatted.txt"),
            sw As New StreamWriter("C:\Temp\formatted.txt")
            Dim counter As Integer = 0
            Dim sampleNo As String = ""
            For Each line As String In sr.ReadToEnd.Split(Environment.NewLine)
                If (counter Mod 3) = 0 Then
                    sampleNo = line.Split(": ")(1).Trim
                Else
                    sw.WriteLine(String.Format("{0}|{1}|{2}", sampleNo, line.Split(" ")(0), line.Split(" ")(1)))
                End If
                counter += 1
            Next
        End Using
    End Sub

End Class
 
Thanks much Matt for the reply....Very helpful. Still see some issues
When I try to run, I am getting "Index was outside the bounds of the array"IndexOutOfRangeException error at the line below
sampleNo = line.Split(": ")(1).Trim
Also my input file is coming out of an instrument as results. So the next time my input can be
SAMPLE NO: 10S-02013
Moisture 13.0
DryMat 87.0
CrdPro 14.0
ADF 33.1
NDF 40.1
dNDF48 15.5
P 0.13
Ca 1.50
K 1.82
Mg 0.27
ASH 10.09
Lignin 8.72
FAT 0.93
TDN 50.5
NEL 0.51
NEM 0.49
NEG 0.27
RFV 104.2
NDFD 33.6
NFC 23.7
TDNL 45.0
RFQ 88.9
NIR 1.0
and then next Sample Numeber, and related values, but the output file will be in same format...
 
Last edited:
Try this then

VB.NET:
Imports System.IO

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Using sr As New StreamReader("C:\Temp\unformatted.txt"),
            sw As New StreamWriter("C:\Temp\formatted.txt")
            Dim sampleNo As String = ""
            For Each line As String In sr.ReadToEnd.Split(Environment.NewLine)
                If line.Trim.StartsWith("SAMPLE NO") Then
                    sampleNo = line.Split(": ")(1).Trim
                Else
                    sw.WriteLine(String.Format("{0}|{1}|{2}", sampleNo, line.Split(" ")(0), line.Split(" ")(1)))
                End If
            Next
        End Using
    End Sub

End Class

Input file

SAMPLE NO: 10S-02013
Moisture 10.1
DryMat 89.9
SAMPLE NO: 10S-02014
Moisture 10.1
DryMat 89.9
SAMPLE NO: 10S-02015
Moisture 13.0
DryMat 87.0
CrdPro 14.0
ADF 33.1
NDF 40.1
dNDF48 15.5
P 0.13
Ca 1.50
K 1.82
Mg 0.27
ASH 10.09
Lignin 8.72
FAT 0.93
TDN 50.5
NEL 0.51
NEM 0.49
NEG 0.27
RFV 104.2
NDFD 33.6
NFC 23.7
TDNL 45.0
RFQ 88.9
NIR 1.0

Output file

10S-02013|Moisture|10.1
10S-02013|DryMat|89.9
10S-02014|Moisture|10.1
10S-02014|DryMat|89.9
10S-02015|Moisture|13.0
10S-02015|DryMat|87.0
10S-02015|CrdPro|14.0
10S-02015|ADF|33.1
10S-02015|NDF|40.1
10S-02015|dNDF48|15.5
10S-02015|P|0.13
10S-02015|Ca|1.50
10S-02015|K|1.82
10S-02015|Mg|0.27
10S-02015|ASH|10.09
10S-02015|Lignin|8.72
10S-02015|FAT|0.93
10S-02015|TDN|50.5
10S-02015|NEL|0.51
10S-02015|NEM|0.49
10S-02015|NEG|0.27
10S-02015|RFV|104.2
10S-02015|NDFD|33.6
10S-02015|NFC|23.7
10S-02015|TDNL|45.0
10S-02015|RFQ|88.9
10S-02015|NIR|1.0
 
Thanks Matt...Your code is just working perfect in debug mode, but at some point, I am still getting "Index was outside the bounds of the array."

One thing When I send you the input text file, it looses its format, when I post this
SAMPLE NO: 10S-02013
Moisture(spaces so that decimal is at 19th position)13.0
Thanks for your help. I appreciate your quick replies.........:D
 
Last edited:
I have attached the original input text file, and the error I am getting.

Thanks for giving me a good start with VB.NET
 

Attachments

  • error.JPG
    error.JPG
    165 KB · Views: 36
  • TODAY.txt
    670 bytes · Views: 32
You're getting hung up on the empty line at the end of the file. Just add a check to see if the line is equal to an empty string.

VB.NET:
Imports System.IO

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Using sr As New StreamReader("C:\Temp\today.txt"),
            sw As New StreamWriter("C:\Temp\formatted.txt")
            Dim sampleNo As String = ""
            For Each line As String In sr.ReadToEnd.Split(Environment.NewLine)
                If line.Trim.StartsWith("SAMPLE NO") Then
                    sampleNo = line.Split(": ")(1).Trim
                Else
                    If line.Trim <> "" Then
                        Dim elements() As String = line.Split({" "}, StringSplitOptions.RemoveEmptyEntries)
                        sw.WriteLine(String.Format("{0}|{1}|{2}", sampleNo, elements(0), elements(1)))
                    End If
                End If
            Next
        End Using
    End Sub

End Class
 
No problem. I'm happy to help out someone who has made a valid effort on their own shows appreciation for the assistance. You'll find out that the others giving advice on this board respond well to these qualities as well.

Hopefully you learned something from this thread and can one day be the one to help out someone else who's stuck.
 
Back
Top