Advertisement
Method | Description |
---|---|
int Seek(int offset, SeekOrigin origin) | This method sets the current position of the file pointer, where:
|
Fields | Description |
---|---|
SeekOrigin.Begin | Sets the file pointer to the beginning of the file, to seek from the beginning of a file. |
SeekOrigin.Current | Sets the file pointer to the current position in the file, to seek from the current position. |
SeekOrigin.End | Sets the file pointer to the end position in the file, to seek from the end position. |
//C# calling the Seek() method of FileStream class to write to a file and to read from it.
using System;
using System.IO;
using System.Text;
class A
{
public static void Main(String[] ar)
{
try
{
//Creating an object of FileStream
FileStream fs = new FileStream("D:\\Textbook8.txt", FileMode.Create);
//Creating a String object
String str = "There is a light at the end of the tunnel, so keep fighting!.";
//Creating a byte array from a String
byte[] bA = Encoding.ASCII.GetBytes(str);
Console.WriteLine("Writing to a file");
foreach(byte bt in bA)
{
//writing one byte at a time to the file.
fs.WriteByte(bt);
}
//Flushing the buffered date to the file
fs.Flush();
//Calling the Seek() method to set the file pointer to the beginning of the file
fs.Seek(0, SeekOrigin.Begin);
int c;
//Calling the ReadByte() method to reading one byte out of a file
Console.WriteLine("Reading the contents of the same file: ");
while((c = fs.ReadByte()) !=-1)
{
//Casting byte to char for displaying the read character on the screen
Console.Write((char)c);
}
//Closing the byte stream i.e. FileStream
fs.Close();
}
catch(IOException e)
{
Console.WriteLine(e);
}
}
}
Writing to a file
Reading the contents of the same file:
There is a light at the end of the tunnel, so keep fighting!.
//C# calling the Seek() method of FileStream class
// to read a file from an offset somewhere in the middle to its end
using System;
using System.IO;
using System.Text;
class A
{
public static void Main(String[] ar)
{
try
{
//Creating an object of FileStream
FileStream fs = new FileStream("D:\\Textbook8.txt", FileMode.Open);
//Calling the Seek() method to set the file pointer 10 offset from the beginning of the file
fs.Seek(10, SeekOrigin.Begin);
int c;
//Calling the ReadByte() method to reading one byte out of a file
Console.WriteLine("Reading the contents of the same file: ");
while((c = fs.ReadByte()) !=-1)
{
//Casting byte to char for displaying the read character on the screen
Console.Write((char)c);
}
//Closing the byte stream i.e. FileStream
fs.Close();
}
catch(IOException e)
{
Console.WriteLine(e);
}
}
}
Reading the contents of the same file:
light at the end of the tunnel, so keep fighting!
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement