none
Reading text file VB.NET RRS feed

  • Question

  • import a txt file and its contents and export it to another file. -- I have already completed this.

    The output file should add a tab followed by a random number between 1 and 100 after each name.

    example:

    Ann 30

    Mike 10

    Edward 22

    When the user clicks a button read in the file you created and give the following:

    number of rows (displayed in label)

    avg of the numbers (displayed in label)

    highest number and who had it (displayed in label)

    So im really just looking for guidance on how to add a tab after the name and code the label outputs. Any guidance is greatly appreciated. Thanks. Below is the first part of what i have so far.

    Private Sub btnGenerateFile_Click(sender As Object, e As EventArgs) Handles btnGenerateFile.Click
            Dim sw As StreamWriter
            Dim sr As StreamReader
            Dim s As String
            Dim i As Integer
            Dim T As String
            Dim inputfile As String
            Dim outputfile As String
    
            inputfile = Application.StartupPath & "\Names.txt"
            outputfile = Application.StartupPath & "\output.txt"
    
            sw = File.CreateText(outputfile)
            sr = File.OpenText(inputfile)
    
            Do While sr.Peek > -1
                s = sr.ReadLine
                T = s.ToUpper
                sw.WriteLine(T)
            Loop
            sr.Close()
            sw.Close()


    • Edited by 70CC07 Thursday, November 15, 2018 6:09 PM
    Thursday, November 15, 2018 5:05 PM

All replies

  • Can you please specify if this is homework or not?

    Reasoning, if this is not homework I would be incline to provide guidence that would not be helpful for homework but would be for non-homework. Same goes for others whom are here to assist.

    Not homework all this can be easily done with lambda or linq in tangent with generics but not suitable for homework.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, November 15, 2018 5:35 PM
    Moderator
  • Hello! This is not homework but was assigned by the teacher as extra practice before our exam comes up. I am looking for guidance on how to extract the information from the txt file such as number of rows, average of all the numbers, etc. into a label. would it be with a &vbtab& ? or would i need &vbcrlf ?
    Thursday, November 15, 2018 6:12 PM
  • Hi

    Here is one way. Check the comments carefully. This is purely for you to get started and is NOT valid for you to submit as your own work.

    Option Strict On
    Option Explicit On
    Public Class Form1
      ' text file has Name,Score
      ' NOTE: the slightly different format
      ' This example uses:
      ' Ann,30
      ' Mike,10
      ' Edward,22
      ' Les,922089
      ' 70CC07,-1000
      ' Freddy,1
      ' Mary,101099
      Dim FilePath As String = "C:\Users\lesha\Desktop\TestText.txt"
      Dim dict As New Dictionary(Of String, Integer)
      Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim lines() As String = IO.File.ReadAllLines(FilePath)
        ' that got all the lines
    
        For Each line As String In lines
          ' now separate lines into Name/Score
          Dim a() As String = line.Split(","c)
    
          ' check if exactly 2 data values
          If Not a.Length = 2 Then Exit For
    
          ' put into Dictionary
          dict.Add(a(0), GetInteger(a(1)))
        Next
    
        ' here, we should have all the Names/
        ' Score as data pairs in Dictionary
        ' so some functions
        Dim max As Integer = dict.Values.Max
        Dim min As Integer = dict.Values.Min
        Dim average As Double = dict.Values.Average
    
        Dim Score70CC07 As Integer = dict("70CC07")
        Dim ScoreLes As Integer = dict("Les")
    
        Dim Highest As String = Nothing
        For Each kvp As KeyValuePair(Of String, Integer) In dict
          If kvp.Value = max Then
            Highest = kvp.Key
          End If
        Next
    
        ' when reaches here, the application
        ' will STOP. At this time, you can use
        ' the mouse and hover over the 
        ' variables above to see their values
        Stop
      End Sub
      Function GetInteger(s As String) As Integer
        ' this function returns a valid
        ' integer OR ZERO if not valid 
        ' Integer string
        Dim v As Integer
        If Integer.TryParse(s, v) Then Return v
        Return 0
      End Function
    End Class
    


    Regards Les, Livingston, Scotland

    Thursday, November 15, 2018 8:12 PM
  • Here is a path. I used a list of names, think of them as names you've gotten already.

    Required class

    Public Class Person
        Public Property Name As String
        Public Property Value As Integer
    End Class
    

    Code

    Imports System.IO
    
    Public Class Form1
        Private fileName As String = Path.Combine(AppDomain.
            CurrentDomain.BaseDirectory, "People.txt")
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
            Dim nameList = New List(Of String) From {"Karen", "Jane", "Mark", "Anne", "Mary", "Bill"}
            Dim sb As New Text.StringBuilder
    
            nameList.ForEach(Sub(pName) sb.AppendLine($"{pName}{vbTab}{CInt(Math.Ceiling(Rnd() * 120)) + 1}"))
            File.WriteAllText(fileName, sb.ToString)
        End Sub
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            Dim theList = New List(Of Person)
    
            Using reader As New FileIO.TextFieldParser(fileName)
    
                reader.TextFieldType = FileIO.FieldType.Delimited
                reader.Delimiters = New String() {vbTab}
                Dim row As String()
                While Not reader.EndOfData
                    row = reader.ReadFields()
                    theList.Add(New Person With {.Name = row(0), .Value = CInt(row(1))})
                End While
            End Using
    
            Dim numberOfRows = theList.Count
    
            Console.WriteLine(numberOfRows)
    
            Dim averageOfNumbers = CInt(theList.Average(Function(x) x.Value))
            Console.WriteLine(averageOfNumbers)
    
            Dim highestNumber = theList.Max(Function(x) x.Value)
            Console.WriteLine(highestNumber)
    
    
        End Sub
    End Class

    You can get the label assignments :-)

    The results

    6
    65
    94


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Thursday, November 15, 2018 8:41 PM
    Moderator