Skip to content
Related Articles

Related Articles

C# Program to Demonstrate the Use of CanRead Property

Improve Article
Save Article
  • Last Updated : 02 Feb, 2022
Improve Article
Save Article

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 CanRead property is one of them. This property is used to check whether the given stream support reading or not. It will return true if the stream support writing, otherwise it will return false.

Syntax:

public override bool CanRead { get; }

Return: The return type of this property is boolean. It will return true if the stream support reading. Or it will return false if the stream is closed or open with write-only access.

Approach:

1. Create two file pointers – file 1 and file2

FileStream file1;
FileStream file2;

2. Get the file1 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 CanRead 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
// CanRead property
using System;
using System.IO;
 
class GFG{
 
static void Main()
{
     
    // Declare two file pointers
    FileStream file1;
    FileStream file2;
     
    // Read 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 read or not
    // Using CanRead property
    if (file1.CanRead)
        Console.WriteLine("able to read");
    else
        Console.WriteLine("not able to read");
     
    // Close first file pointer
    file1.Close();
     
    // Check file pointer 2 is able to read or not
    // Using CanRead property
    if (file2.CanRead)
        Console.WriteLine("able to read");
    else
        Console.WriteLine("not able to read");
         
    // Close second file pointer
    file2.Close();
}
}


Output:

able to read
not able to read

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!