read the first 5 characters of file

S-Soft 666 Reputation points
2022-11-13T19:23:43.683+00:00

hi,
user might select any file type, with or without extension, need to get the 5 characters of file without opening and reading the whole file, like ReadAllText
help please :)

Developer technologies VB

Locked Question. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments
{count} votes

4 answers

Sort by: Newest
  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  2. WayneAKing 4,931 Reputation points
    2022-11-14T00:39:53.707+00:00

    In my last example, note that the for loop to get the bytes
    can be replaced with a ReadBytes(5) instruction:

    'For index = 0 To 4  
    '    bArray(index) = reader.ReadByte  
    'Next  
    bArray = reader.ReadBytes(5)  
      
    
    • Wayne
    0 comments No comments
  3. WayneAKing 4,931 Reputation points
    2022-11-14T00:28:03.427+00:00

    user might select any file type, with or without extension,
    need to get the 5 characters of file

    It may depend on what you mean by "characters".

    Do you mean one byte, as in a raw file dump?

    Or do you really mean characters, such as 5 ASCII characters or
    5 Unicode characters, etc.

    For getting the first 5 bytes from any file, including binary
    types such as .exe, .dll, etc. try this code.

    NOTE: For brevity I have omitted all error checks. For robust
    code you will need to add them. Such as file open failures,
    files less than 5 bytes long, etc.

    For testing in the IDE, the file test.exe will need to be in
    the same folder as the program's .exe - such as ..\bin\debug

    Imports System.IO  
    Module Module1  
      
        Sub Main()  
            Dim bArray(4) As Byte  
            Dim filename As String = "test.exe"  
            Dim stream = File.Open(filename, FileMode.Open)  
            Dim reader = New BinaryReader(stream)  
            For index = 0 To 4  
                bArray(index) = reader.ReadByte  
            Next  
            For index = 0 To 4  
                Console.WriteLine("{0:X2}", bArray(index))  
            Next  
        End Sub  
      
    End Module  
      
    
    • Wayne
    1 person found this answer helpful.
    0 comments No comments
  4. Viorel 122.5K Reputation points
    2022-11-13T19:58:58.733+00:00

    Try something like this:

    Dim characters(4) As Char  
      
    Using f = File.OpenText("C:\MyFile.txt")  
        f.Read(characters, 0, 5)  
    End Using  
    
    Dim text As String = String.Concat(characters).TrimEnd(Chr(0))  
    
    1 person found this answer helpful.