File.Open(String, FileMode, FileAccess) is an inbuilt File class method that is used to open a FileStream on the specified path with the specified mode and access with no sharing.
public static System.IO.FileStream Open (string path, System.IO.FileMode mode, System.IO.FileAccess access);
Parameter: This function accepts three parameters which are illustrated below:
- path: This is the specified file to open.
- mode: This mode value specifies whether a new file is created if one does not exist, and also determines whether the existing file’s contents are retained or overwritten.
- access: This value specifies the operations that can be performed on the file..
- ArgumentException: The specified path is a zero-length string, contains only white space, or one or more invalid characters as defined by InvalidPathChars.OR access specified Read and mode specified Create, CreateNew, Truncate, or Append.
- 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.
- IOException: An I/O error occurred while opening the file.
- UnauthorizedAccessException: The path specified a file that is read-only and access is not Read. OR the path specified a directory. OR the caller does not have the required permission. OR the mode is Create and the specified file is a hidden file.
- ArgumentOutOfRangeException: The mode or access specified an invalid value.
- FileNotFoundException: The file specified in the path was not found.
- NotSupportedException: The path is in an invalid format.
Return Value: Returns an unshared FileStream that provides access to the specified file, with the specified mode and access.
Below are the programs to illustrate the File.Open(String, FileMode, FileAccess) method.
Program 1: Below code creates a temporary file, writes some specified contents into it, open that file and print its contents.
GFG is a CS Portal.
Program 2: Initially, a file file.txt is created with some contents shown below-
This below code will open the file file.txt and will print its contents.