User Tools

Site Tools


read_file

Read a file

If you need to read or write to files and wish to keep the entire file in memory, you can use the static methods of the System.IO.File class:

(the following static methods are only a small fraction of the functionality this class offers - please read the full documentation of this class!)

  • ReadAllBytes() will return you a byte array of the specified file
  • ReadAllLines() will return a string array of all lines of the specified file
  • ReadAllText() will return a string with the content of the file
  • WriteAllBytes() will write the specified byte array to the file
  • WriteAllLines() will write the string array to the file
  • WriteAllText() will write the string to the file

Please pay attention to the encoding with all methods that deal with strings. All these methods have a version that lets you specify the enconding, and one without. You should prefer to specify it!

A sample:

using System.Text
using System.IO

local cString as string
local aBytes as byte[]
local cBuffer as string  
	
cString := "Hello world!"
	
File.WriteAllText( cFileName, cString )
aBytes := File.ReadAllBytes( cFileName )
cBuffer := System.Text.Encoding.Default:GetString( aBytes )
System.Console.WriteLine( "Bytes, without:" + cBuffer + ", file length: " + FileInfo{ cFileName }:Length:ToString() )  
	
File.WriteAllText( cFileName, cString, Encoding.ASCII )
aBytes := File.ReadAllBytes( cFileName )
cBuffer := System.Text.Encoding.ASCII:GetString( aBytes )
System.Console.WriteLine( "Bytes, ASCII:" + cBuffer + ", file length: " + FileInfo{ cFileName }:Length:ToString() )  

File.WriteAllText( cFileName, cString, Encoding.Default )
aBytes := File.ReadAllBytes( cFileName )
cBuffer := System.Text.Encoding.Default:GetString( aBytes )
System.Console.WriteLine( "Bytes, Default:" + cBuffer + ", file length: " + FileInfo{ cFileName }:Length:ToString() )  
	
File.WriteAllText( cFileName, cString, Encoding.Unicode )
aBytes := File.ReadAllBytes( cFileName )
cBuffer := System.Text.Encoding.Unicode.GetString( aBytes )
System.Console.WriteLine( "Bytes, Default:" + cBuffer + ", file length: " + FileInfo{ cFileName }:Length:ToString() )  
	
File.WriteAllText( cFileName, cString, Encoding.UTF32 )
aBytes := File.ReadAllBytes( cFileName )
cBuffer	:= System.Text.Encoding.UTF32.GetString( aBytes )
System.Console.WriteLine( "Bytes, Default:" + cBuffer + ", file length: " + FileInfo{ cFileName }:Length:ToString() )  
	
cBuffer := System.Text.Encoding.ASCII.GetString( aBytes )
System.Console.WriteLine( "Bytes, Default:" + cBuffer + ", file length: " + FileInfo{ cFileName }:Length:ToString() )

This piece of code produces the following output:

read_file.txt · Last modified: 2018/01/27 21:35 by wolfgangriedmann