Demonstrate random access file : FileStream : File Directory Stream C# Examples


C# Examples » File Directory Stream » FileStream »

 

Demonstrate random access file









    
using  System;  
using  System.IO;    
  
class  MainClass  {  
    public  static  void  Main()  {  
        FileStream  f;  
        char  ch;  
  
        try  {  
            f  =  new  FileStream("random.dat",  FileMode.Create);  
        }  
        catch(IOException  exc)  {  
            Console.WriteLine(exc.Message);  
            return  ;  
        }  
  
        //  Write  the  alphabet.            
        for(int  i=0;  i  <  26;  i++)  {  
            try  {  
                f.WriteByte((byte)('A'+i));  
            }    
            catch(IOException  exc)  {  
                Console.WriteLine(exc.Message);  
                return  ;  
            }  
        }  
  
        try  {  
            f.Seek(0,  SeekOrigin.Begin);  //  seek  to  first  byte  
            ch  =  (char)  f.ReadByte();  
            Console.WriteLine("First  value  is  "  +  ch);  
  
            f.Seek(1,  SeekOrigin.Begin);  //  seek  to  second  byte  
            ch  =  (char)  f.ReadByte();  
            Console.WriteLine("Second  value  is  "  +  ch);  
  
            f.Seek(4,  SeekOrigin.Begin);  //  seek  to  5th  byte  
            ch  =  (char)  f.ReadByte();  
            Console.WriteLine("Fifth  value  is  "  +  ch);  
  
            Console.WriteLine();  
  
        }    
        catch(IOException  exc)  {  
            Console.WriteLine(exc.Message);  
        }  
    
        Console.WriteLine();  
        f.Close();  
    }  
}
    
   
  
   



Output

First value is A
Second value is B
Fifth value is E


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo File Directory Stream
» FileStream