C# Filestream

Reading and writing files is an essential part of many programs. There is also creating and deleting files, moving files and getting file and directory information. All input and output in the .NET Framework involves the use of streams. A stream is an abstract representation of a serial device. Serial means sequentially, one byte at a time. There are two types of streams: output and input.

Output — Output streams are used when data is written to some external destination, which can be a physical disk file, a network location, a printer, or another program.



class Program  {  // Filestream 
    static void Main(string[] args)  {
        byte[] byteData = new byte[900];
        char[] charData = new char[900];
        try {
            string strFileName = "Program.cs";
            FileStream aFile = new FileStream("../../" + strFileName, FileMode.Open);
            // move to the 174th byte starting from the first byte:
            aFile.Seek(174, SeekOrigin.Begin);
            // Seek takes 2 paramters; how far to move the pointer in bytes and
            // where to start counting from in the form of a value from the SeekOrigin enumeration
            // The SeekOrigin enumeration contains three values: Begin, Current and End.
            aFile.Read(byteData, 0, 900);
            // The FileStream class deals exclusively with raw bytes, making it useful for reading
            // any kind of data file including text files, sound files and images.
        catch (IOException e) {
            WriteLine("An IO exception has been thrown!");
        Decoder d = Encoding.UTF8.GetDecoder();
        // GetChars() method takes an array of bytes and converts it to an array of characters
        // so that we can write it to the console.
        d.GetChars(byteData, 0, byteData.Length, charData, 0);

Leave a comment

Your email address will not be published. Required fields are marked *