Home »
.Net »
C# Programs
C# - FileStream.Seek() Method | Random Access File
In this tutorial, we will learn how to access the file randomly using the Seek() method in C#?
Submitted by IncludeHelp, on November 17, 2017 [Last updated : March 27, 2023]
C# FileStream.Seek() Method
This is a method of "FileStream" class, it is used to set the current position file stream to given value.
Syntax
long Seek(long offset, SeekOrigin origin);
Parameter(s)
- Offset : move file stream to given value.
- Origin : It tells the origin, it may be start, current and end.
Example of accessing file randomly using Seek() Method in C#
using System;
using System.IO;
namespace ConsoleApplication1 {
class Program {
static void Main() {
byte[] b1 = {10, 20, 24, 13, 15, 17};
byte[] b2 = new byte[6];
byte large = 0;
FileStream f1;
f1 = new FileStream("abc.txt", FileMode.Create, FileAccess.Write);
f1.Write(b1, 0, 6);
f1.Close();
f1 = new FileStream("abc.txt", FileMode.Open, FileAccess.Read);
f1.Seek(3, SeekOrigin.Begin);
f1.Read(b2, 0, 3);
large = b2[0];
for (int i = 1; i < b2.Length; i++) {
if (large < b2[i])
large = b2[i];
}
Console.WriteLine("Largest Item is : " + large);
f1.Close();
}
}
}
Output
Largest Item is : 17
Explanation
In this program, we are performing read and write operation into file and moving stream to 3rd position from start and find largest element.
In above program, we need to remember, when we use "FileStream" class then we need to include System.IO namespace in the program.
C# FileStream Class Program »