Read and write from a file


StreamReader

StreamReader is a file pointer.We can create a StreamReader object to open the file. After the file is opened, the StreamReader method Read can be used to obtain the next characterand ReadToEnd method reads the whole file. The Peek property allow you to look ahead one character to determine whether the end of the file has been reached. After the file contents are read, the Close method closes the stream.

codesnippet below shows how to use StreamReader to read content



 StreamReader objreader = File.OpenText ( filename ) ;
 String str = objreader .ReadToEnd(); 
reader.Close();  
  

File Stream

Filestream Write and Read

If you need to write byte data to a file,We can use FilestreamClass.It has Write and WriteByte methods.if we have a single byte to be written we can use WriteByte method. The Write method accepts an array of bytes that can be written to the file.Similarly We have Read And ReadByteMethod to read from filestream

Write method Example


FileStream fStream = File.Open("Filestream.txt",FileMode.OpenOrCreate);
      
        if(fStream.CanWrite)
        {
           
          byte[] ArrayOfBytes = new byte[2] {67, 68};
          fStream.Write(ArrayOfBytes, 0, ArrayOfBytes.Length);
          
               
        }
        
        fStream.Close();
          

Read Filestream

  if(fStream.CanRead)
          {
            
            byte[] ArrayRead= new byte[fStream.Length];
            fStream.Read(ArrayRead, 0, ArrayRead.Length);     
   }
        
        fStream.Close();
      

WriteByte method

 fStream.WriteByte(68);
      

ReadByte
Stream creates a new single-byte array and then calls Read.It returns an integer read from the binary stream specified by stream

byte retReadValue= (byte)fStream.ReadByte();
      

SeekMethod

FileStream.Seek method to move to a specific location.The Seek() method allows you to set the file position indicator to any point within a file.

SeekOrigin.Begin is used to Seek from the beginning of the file.
SeekOrigin.Current is used to Seek from the current location.
SeekOrigin.End is used to Seek from the end of the file


fileStream.Seek(0, SeekOrigin.Begin); 
int FirstValue= (int) fileStream.ReadByte();
		//Retrieves the first byte	
 

We know that In order to write characters to that stream, you’d need to convert them to a string of bytes. In that case we use the help of StreamReader It takes a sequence of characters and an encoding, and turns it into a sequence of bytes.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: