File.OpenWrite() Method in C# with Examples
Last Updated :
25 Feb, 2021
File.OpenWrite(String) is an inbuilt File class method that is used to open an existing file or creates a new file for writing.
Syntax:
public static System.IO.FileStream OpenWrite (string path);
Parameter: This function accepts a parameter which is illustrated below:
- path: This is the specified text file that is going to be opened for writing.
Exceptions:
- UnauthorizedAccessException: The caller does not have the required permission. OR the path specified a read-only file or directory.
- ArgumentException: The path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars.
- ArgumentNullException: The path is null.
- PathTooLongException: The specified path, file name, or both exceed the system-defined maximum length.
- DirectoryNotFoundException: The specified path is invalid.
- NotSupportedException: The path is in an invalid format.
Return Value: Returns an unshared FileStream object on the specified path with Write access.
Below are the programs to illustrate the File.OpenWrite(String) method.
Program 1: Initially, no file is created. Below code, itself creates a file gfg.txt, writes some texts into it, and prints.
C#
using System;
using System.IO;
using System.Text;
class GFG {
public static void Main()
{
string path = @"gfg.txt" ;
using (FileStream fs = File.OpenWrite(path))
{
Byte[] info = new UTF8Encoding( true ).GetBytes( "GFG is a computer science portal." );
fs.Write(info, 0, info.Length);
}
using (FileStream fs = File.OpenRead(path))
{
byte [] b = new byte [1024];
UTF8Encoding temp = new UTF8Encoding( true );
while (fs.Read(b, 0, b.Length) > 0) {
Console.WriteLine(temp.GetString(b));
}
}
}
}
|
Output:
GFG is a computer science portal.
The above code gives the above output and creates a file which is shown below:
Program 2: Initially, a file file.txt is created with some contents shown below-
The below code will overwrite the file contents with other specified contents then final contents will be printed.
CSharp
using System;
using System.IO;
using System.Text;
class GFG {
public static void Main()
{
string path = @"file.txt" ;
using (FileStream fs = File.OpenWrite(path))
{
Byte[] info = new UTF8Encoding( true ).GetBytes( "GFG is a CS portal." );
fs.Write(info, 0, info.Length);
}
using (FileStream fs = File.OpenRead(path))
{
byte [] b = new byte [1024];
UTF8Encoding temp = new UTF8Encoding( true );
while (fs.Read(b, 0, b.Length) > 0) {
Console.WriteLine(temp.GetString(b));
}
}
}
}
|
Output:
GFG is a CS portal.
Share your thoughts in the comments
Please Login to comment...