I want to calculate the instance of * in the text file....

Dani AI

Generated

asked how to count '' in a text file and pointed toward reading the file and tallying matches. Below are two concise, practical VB.NET options: one for small files (simple and quick) and a buffered streaming version for very large files. Both handle typical errors and use the correct Char literal (`""c`).

' Simple - reads entire file (good for small/medium files)
Imports System.Linq

Dim path As String = "C:\path\to\file.txt"
Try
    Dim text As String = IO.File.ReadAllText(path)
    Dim starCount As Integer = text.Count(Function(ch) ch = "*"c)
    Console.WriteLine("Found " & starCount & " '*' characters.")
Catch ex As Exception
    Console.WriteLine("Error: " & ex.Message)
End Try
' Buffered streaming - safe for very large files (low memory)
Dim path As String = "C:\path\to\file.txt"
Dim total As Long = 0

Using sr As New IO.StreamReader(path)
    Dim buffer(8191) As Char
    Dim read As Integer = sr.Read(buffer, 0, buffer.Length)
    While read > 0
        For i As Integer = 0 To read - 1
            If buffer(i) = "*"c Then total += 1
        Next
        read = sr.Read(buffer, 0, buffer.Length)
    End While
End Using

Console.WriteLine("Found " & total & " '*' characters.")

Notes and troubleshooting: prefer the streaming method when files approach available memory limits. Use Long for counters if extremely large files are expected. The '*' character is U+002A, so matching "*"c works across common encodings; if a non-text (binary) file is being processed, consider reading bytes and comparing to &H2A. Common zero-count causes are wrong path, missing read permissions, or the file using a different encoding/character (inspect the raw bytes if results look wrong). Exceptions such as FileNotFoundException and UnauthorizedAccessException should be handled as shown.

You may read the file char by char and increment a counter if the symbol '*' is encountered

Or read all the lines and store in a string and then use any string operation to do the same

Can't post any codes as I don't have any "hands - on" experience on VB.net

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.