Open In App

C# Program to Demonstrate the Use of CanSeek Property

Last Updated : 01 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

FileStream class is used to perform read and write operations in a file. It provides full support for both synchronous and asynchronous read and write operations. This class provides different types of methods and properties and the CanSeek property is one of them. This property is used to find a value that determines whether the current stream supports seeking or not. If the returned value is true then that means the current stream supports seeking, Or if the returned value is false then that means the current stream does not support seeking.  

Syntax:

public override bool CanSeek { get; }

Return: The return type of this property is Boolean, either true or false. 

Approach:

1. Create two file pointers – file 1 and file2

FileStream file1;
FileStream file2;

2. Get file 1 with sravan.txt with Read access and vignan.txt with Write access

file1 = new FileStream("sravan.txt", FileMode.Open, FileAccess.Read);
file2 = new FileStream("vignan.txt", FileMode.Open, FileAccess.Write);

Here, Open property is used to open the file, Read property is used to read the file, and Write property is used to write in the file.

3. Check the both files are able to Read or not using CanSeek Property

if (file1.CanRead)
    Console.WriteLine("able to read");
else
    Console.WriteLine("not able to read");
if (file2.CanRead)
    Console.WriteLine("able to read");
else
    Console.WriteLine("not able to read");

4. Close both the files

Example:

C#




// C# program to demonstrate the working of CanSeek property
using System;
using System.IO;
  
class GFG{
  
static void Main()
{
      
    // Declare two file pointers
    FileStream file1;
    FileStream file2;
      
    // Read given files
    file1 = new FileStream("sravan.txt", FileMode.Open,
                           FileAccess.Read);
    file2 = new FileStream("vignan.txt", FileMode.Open,
                           FileAccess.Write);
  
    // Check file pointer 1 is able to seek or not
    // Using the CanSeek property
    if (file1.CanSeek)
        Console.WriteLine("able to seek");
    else
        Console.WriteLine("not able to seek");
  
    // Close first file pointer
    file1.Close();
      
    // Check file pointer 2 is able to seek or not
    // Using the CanSeek property
    if (file2.CanSeek)
        Console.WriteLine("able to seek");
    else
        Console.WriteLine("not able to seek");
          
    // Close second file pointer
    file2.Close();
}
}


Output:

able to seek
able to seek


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads