generally speaking, use C # the program reads and writes a file that requires the following 5 a step.
- Creates a file stream.
- Create a reader or writer.
- Perform read and write operations.
- Close the reader or writer.
- Closes the file stream.
When you perform a file operation, you need to reference the System.IO namespace in your class.
To create a file stream:
The stream is an object for data transfer, and the file used here drains the FileStream class.
FileStream File Object = new FileStream (string FilePath, FileMode);
FilePath is used to specify the file to manipulate, FileMode specifies the mode of the open file, which is an enumeration type.
The different members of the enumeration are as follows:
Create:: Creates a new file with the specified name. If the file exists, overwrite the old file.
CreateNew: Creates a new file, and if the file exists an exception occurs, the hint file already exists.
Open: Opens a file that uses this enumeration when the specified file must exist, otherwise an exception will occur.
OpenOrCreate: Similar to the previous one, except that if the file does not exist, create a new file with the specified name and open it.
Append: Open an existing file and append the content at the end.
File Reader/Writer:
The StreamWriter class is called a writer, and the StreamReader class is called a reader.
After you create the file stream, you create the reader or writer. Used to write data to a file stream.
Creating a writer
StreamWriter MYSW = New StreamWriter (MYFS);
Mysw.writer (content);
After the writer is created, the method that invokes it writes the content to the file stream.
Create reader
StreamReader MYSR = New StreamReader (MYSR, Encoding.defualut);
Encoding.default to get the current encoding of the operating system
Content = Mysr.readtoend ();
When you are ready to read the file data, the FileMode of the file stream should be set to FileMode.Open instead of FileMode.Create.
Note: The method of closing the writer and reader must be called.
File and directory operations:
The file class and directory classes are static classes that do not need to be instantiated when they are used, but are called directly using the class name. Method ().
Static classes contain only static methods and cannot be used to create instances of static classes using the New keyword.
Because static methods perform security checks when they are used, you might consider using FileInfo and DirectoryInfo non-static classes if you want to use a file object multiple times.
C # File operations