C # Study Notes: File Operations
How to read and write files:
Generally speaking, using a C # program to read and write a file requires the following five basic steps:
(1) create a file stream.
(2) create a reader or writer
(3) perform read/write operations
(4) Close the reader or writer
(5) close the file stream
Namespace required: using system. IO;
Reader:
// Create a file stream
Filestream myfs = new filestream ("path", filemode. Open );
// Create a reader and pass in a file stream
Streamreader mysw = new streamreader (myfs );
// Read all content. The returned value is string.
Mysw. readtoend ();
// Close the reader
Mysw. Close ();
// Close the file stream
Myfs. Close ();
Writer:
// Create a file stream
Filestream myfs = new filestream ("path", filemode. Create );
// Create a reader and pass in a file stream
Streamreader mysw = new streamreader (myfs );
// Write the entered content to a file and save it to the file in the path in myfs.
Mysw. Write ("text value ");
// Close the writer
Mysw. Close ();
// Close the file stream
Myfs. Close ();
To close the sequence, you must first close the reader before closing the file stream. The order cannot be wrong!
----------------------------------- File stream -----------------------------------
The first step to read and write files is to create a file stream. A stream is an object used for data transmission. The file stream used here is a filestream class, which is mainly used to read and write data in files. When creating a file stream, you must specify parameters in its constructor.
Syntax:
Filestream file object = new filestream (string filepath, filemode );
Here, filepath is used to specify the file to be operated, while filemode is used to specify the file opening mode, which is an enumeration type. The enumerated members are as follows:
Create: create a file by name. If the file exists, rewrite the old file.
Createnew: create a file. If the file exists, an exception occurs, prompting that the file already exists.
Open: open a file. When this enumeration value is used, the specified file must exist; otherwise, an exception occurs.
.
Openorcreate: openorcreate is similar to the open member, but if the file does not exist, create a file with the specified name and open it.
Append: open an existing file and Append content to the end of the file.
Filemode enumeration has other Members. We will not list them here.
Invalid path:
C # the program does not support "C: \ text.txt ".
Solution:
(1) change the path to "C: \ text.txt ". This is the standard format supported by C #.
(2) @ "C: \ text.txt", using the Escape Character @
--------------------------------- File reader ---------------------------------
Streamwriter
The main method of writer is as follows:
Streamwriter. Write (); used to write the stream. This stream is the created stream.
Streamwriter. writeline (); used to write a row of data.
Streamwriter. Close (); used to close the writer
Streamreader
The main method of the reader is as follows:
Streamreader. readtoend (); returns a string from the current position to the end.
Streamreader. Readline (); used to read a row of data in the file stream, returns a string
Streamreader. Close (); used to close the reader
--------------------------------- Garbled problem ---------------------------------
The encoding class specifies the character encoding. The encoding class is located in the system. Text namespace and used to represent character encoding.
You can use static members of the encoding class to specify the encoding format. For example:
Encoding. utf8: Get encoding in UTF-8 format
Encoding. Default: Get the current encoding of the Operating System
You can also use the static method getencoding (string name) of the encoding class to specify the character encoding. The parameter name must be the encoding name supported by C. For example:
Streamreader mysw = new streamreader (myfs, encoding. getencoding ("big5 "));
The following are common codes:
(1) ASCII: American Standard Code for information exchange. Applicable to English only, but not outside English
(2) ANSI: It is backward compatible with ASCII and reserved for processing special characters.
(3) gb2313: the Chinese character encoding standard of the Chinese National Standard. The Chinese characters included in the standard can basically meet the computer processing requirements of Chinese characters. However, traditional Chinese encoding is not supported. Later, GBK and big5 character sets were added.
(4) UNICODE: A character encoding scheme developed by international organizations to accommodate all texts and symbols in the world. Unicode encoding occupies a large amount of space. Therefore, some character sets in intermediate format appear. They are called universal conversion formats, namely UTF (Universal Transformation Format ). The existing UTF format has UTF-7, UTF-8, UTF-16, UTF-32. UTF-8 is a variable-length character encoding of Unicode and has now been standardized as RFC 3629. The UTF-8 allows different computers to transmit texts of different languages and encodings over the network, enabling dual-byte Unicode to be correctly transmitted in an existing single-byte system. By default, C # supports UTF-8 encoding.
---------------------------- File and directory operations ------------------------------
File: used to move, copy, and delete files.
Common Methods of File class
Method description
Exists (string path) is used to check whether the specified file Exists. The bool value is returned.
Copy (string path, string path) copies the content in the source file of the specified path to the target file,
If the target file does not exist, create a new file in the specified path.
Move (string path, string path) to Move the specified file to a new path
Delete (string path) deletes a specified file. If the specified file does not exist, no exception is thrown.
Directory class: Directory class is used to operate folders
Common Methods of Directory classes
Method description
Exists (string path) is used to check whether the specified folder Exists on the disk.
Move (string path, string path) is used to Move files, directories, and content to a new location.
Delete (string path) deletes a specified directory. If the bool value is true, Delete the subdirectory.
All contents in
Both File and Directory classes belong to static classes and do not need to be instantiated.
FileInfo: The FileInfo class and File class have similar functions, but need to be instantiated.
FileInfo fi = new FileInfo (path); // you need to pass in the file path when instantiating
Common FileInfo Methods
Attribute description
Exists is used to check whether the specified file exists. The bool value is returned.
Extension: Get the string representing the file extension
Get File Name
Fullname: complete directory for obtaining directories or files
Method description
Copyto (string path) copies an existing file to a new file and does not allow overwriting of the existing file. Delete ()
Permanently delete an object
MoveTo (string path) moves the specified file to a new path
Directoryinfo class: The directoryinfo class is similar to the Directory class and needs to be instantiated.
Directoryinfo di = new directoryinfo (PATH); // when instantiating
You need to input the folder path
// Return the subdirectory of the current directory
Directoryinfo [] subdir = Di. getdirectories ();
// Returns the file list of the current directory.
Fileinfo [] Fi = Di. GetFile ();
(1) getdirectories (): The directoryinfo call returns an array of objects, and the Directory call returns an array of subdirectories.
(2) GetFile (): The directoryinfo call returns an array of objects, and the Directory call returns an array of subdirectories.
How do I choose fileinfo, file, directoryinfo, and directory classes?
A: both the file class and Directory class are static classes. security checks are performed every time a method is called. Therefore, if you want to perform multiple operations on a file or folder, the fileinfo and directoryinfo classes are preferred.
----------------------------------- Summary -----------------------------------
(1) Five Steps for reading and writing a file: create a file stream, create a reader, read and write a file, close the reader, and close the file stream.
(2) The file stream class is filestream. When creating a file stream, you must specify the path of the Operation text, file opening mode, and file access mode.
(3) streamwriter is a writer and stramreader is a reader. You can directly use the reader to read and write text files. You do not need to create file streams, but it is not easy to control how the text is opened and accessed.
(4) The File class is used to operate files, such as copying, moving, and deleting files. The Directory class is used to operate folders. They are static classes.
(5) Static classes only contain static members. Non-static classes can contain static members. Static classes cannot contain instance members. Non-static classes can contain instance members; the static class uses the class name to access its members, and the non-static class uses its instance object to access the members.
(6) The fileinfo class has similar functions as the file class, and can also perform basic operations on files. The difference is that the file class cannot instantiate objects. If you want to reuse a file object multiple times, you can use the fileinfo class first, because security check is not always required.
(7) The directoryinfo class has similar functions as the Directory class to perform basic operations on folders. If you want to reuse a directory object multiple times, consider using the instance method of the directoryinfo class.