Home  |  Delphi .net Home  |  System.IO.BinaryReader  |  ReadString Method
ReadString  
Method  
Reads a string from the current stream
BinaryReader Class
System.IO NameSpace
CF1.  Function ReadString ( ) : String;
CF : Methods with this mark are Compact Framework Compatible
Description
If the current stream has not been exhausted, a string is returned. The next byte in the string holds the string length (in the first 7 bits), folowed by the string in the following bytes.
 
The stream position is updated accordingly.
Microsoft MSDN Links
System.IO
System.IO.BinaryReader
 
 
A simple example
program Project1;
{$APPTYPE CONSOLE}

uses
  System.IO;

var
  MyFileStream  : System.IO.FileStream;
  MyFileWriter  : System.IO.BinaryWriter;
  MyFileReader  : System.IO.BinaryReader;
  MyString      : String;

begin
  // Create and open our binary file as a stream
  MyFileStream := System.IO.File.Open('C:DelphiBasics.txt',
                                      System.IO.FileMode.Create);

  // Create a BinaryWriter to allow writing to this file
  MyFileWriter := System.IO.BinaryWriter.Create(MyFileStream);

  // Write to the file
  MyFileWriter.Write('ABC');
  MyFileWriter.Write(3);      // Simulated string length
  MyFileWriter.Write('D');    // String of 3 characters
  MyFileWriter.Write('E');
  MyFileWriter.Write('F');

  // Close the writer and the stream
  MyFileWriter.Close;
  MyFileStream.Close;

  // Reopen the stream for reading
  MyFileStream := System.IO.File.Open('C:DelphiBasics.txt',
                                      System.IO.FileMode.Open);

  // Create a BinaryReader to allow the file to be read back
  MyFileReader := System.IO.BinaryReader.Create(MyFileStream);

  // Try to read String values from the file
  try
    while 1 = 1 do
    begin
      MyString := MyFileReader.ReadString;
      Console.WriteLine(MyString);
    end;
  except
    On E : Exception do
      Console.WriteLine('End of file');
  end;

  // Close the reader and the stream
  MyFileReader.Close;
  MyFileStream.Close;

  Console.Readline;
end.
Show full unit code
  ABC
  DEF
  End of file
 
 
Delphi Programming © Neil Moffatt All rights reserved.  |  Contact the author