C# Program to Demonstrate the Use of CanWrite Property
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 CanWrite property is one of them. This property is used to check whether the given stream support writing or not. It will return true if the stream support writing, otherwise it will return false.
Syntax:
public override bool CanWrite { get; }
Return: The return type of this property is boolean. It will return true if the stream support writing. Or it will return false if the stream is closed or open with read-only access.
Approach:
1. Create two file pointers – file1 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 CanWrite Property
if (file1.CanWrite)
Console.WriteLine("able to write");
else
Console.WriteLine("not able to write");
if (file2.CanWrite)
Console.WriteLine("able to write");
else
Console.WriteLine("not able to write");
4. Close both the files
Example:
C#
using System;
using System.IO;
class GFG{
static void Main()
{
FileStream file1;
FileStream file2;
file1 = new FileStream( "sravan.txt" , FileMode.Open,
FileAccess.Read);
file2 = new FileStream( "vignan.txt" , FileMode.Open,
FileAccess.Write);
if (file1.CanWrite)
Console.WriteLine( "able to write" );
else
Console.WriteLine( "not able to write" );
file1.Close();
if (file2.CanWrite)
Console.WriteLine( "able to write" );
else
Console.WriteLine( "not able to write" );
file2.Close();
}
}
|
Output:
not able to write
able to write
Last Updated :
28 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...