1. Home
  2. Computing & Technology
  3. Delphi Programming
Delphi for .NET FCL Examples Reference
FileStream class namespace
System.IO
Declaration
type FileStream = class(Stream)
Description
Exposes a Stream around a file, supporting both synchronous and asynchronous read and write operations.
Example
The following example demonstrates some of the FileStream constructors:
program System_IO_FileStream;

{$APPTYPE CONSOLE}
{$AUTOBOX ON}

uses System.IO, System.Text;

type
  TByteArray = array of byte;

  FileStreamTest = class
  private
    class procedure AddText(fs : FileStream; value : string);
  public
    class procedure Main;
  end;

{ FileStreamTest }

class procedure FileStreamTest.AddText
   (fs: FileStream; value: string);
var
  info : TByteArray;
begin
  info := UTF8Encoding.Create(true).GetBytes(value);
  fs.Write(info, 0, System.Array(info).Length);
end; //FileStreamTest.AddText

class procedure FileStreamTest.Main;
var
  fs : FileStream;
  path : string;
  i : integer;
  ba : TByteArray;
  temp: UTF8Encoding;
begin
  path := 'c:\temp\MyTest.txt';

  // Delete the file if it exists.
  if &File.Exists(path) then &File.Delete(path);

  //Create the file.
  fs :=  System.IO.FileStream.Create(path, FileMode.CreateNew);
  try
    AddText(fs, 'This is some text');
    AddText(fs, 'This is some more text,');
    AddText(fs, #13#10 + 'and this is on a new line');
    AddText(fs, #13#10 + 'The following is 
                a subset of characters:' + #13#10);

    for i := 1 to 199 do
    begin
      AddText(fs, Convert.ToChar(i).ToString());

      //Split the output at every 10th character.
      if (Math.IEEERemainder
           (Convert.ToDouble(i), 10) = 0) then
      begin
        AddText(fs, #13#10);
      end;
    end;
  finally
    fs.Free;
  end;

  //Open the stream and read it back
  fs := System.IO.File.OpenRead(path);
  try
    SetLength(ba, 1024);
    temp := UTF8Encoding.Create(true);
    while (fs.Read(ba,0,SizeOf(ba)) > 0) do
      Console.WriteLine(temp.GetString(ba));
  finally
    fs.Free;
  end;

end; //FileStreamTest.Main

begin
  FileStreamTest.Main;
end.
Example output
This is some textThis is some more text,
and this is on a new line
The following is a subset of characters:
........	
..
.......
..........
. !"#$%&'(
)*+,-./012
3456789:;<
=>?@ABCDEF
GHIJKLMNOP
QRSTUVWXYZ
[\]^_`abcd
efghijklmn
opqrstuvwx
yz{|}~??
ƒ????ˆ????
?????????
?˜??????? 
!cL¤Y¦§¨©a
«¬­®—°±23´
µ¶·¸1o»113
?AÁÂAÄAAÇ

Looking for Delphi for .NET demos / source code samples? Look no further, Delphi for .NET FCL Examples Reference is what you are searching for!

Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming

©2009 About.com, a part of The New York Times Company.

All rights reserved.