File.OpenWrite() Method in C# with Examples
File.OpenWrite(String) is an inbuilt File class method that is used to open an existing file or creates a new file for writing.
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.
- 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.
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.
GFG is a CS portal.