C # Introduction to common file read/write classes

Source: Internet
Author: User

First, you must be familiar with file and folder operations in. net. File and directory are the two most important classes. Understanding them will greatly facilitate the implementation of subsequent functions.
This section briefly introduces two. Net classes related to the file system.
The system. Io. File class and system. Io. fileinfo class provide various operations on files. The system. Io namespace must be referenced during use. The following describes the main attributes and methods of a program instance.
(1) file opening method: file. open ()
The statement of this method is as follows:
Public static filestream open (string path, filemode Mode)
The following code opens the file named newfile.txt in the C: \ tempuploadsdirectory and writes hello to the file.
Private void openfile ()
{
Filestream. textfile = file. Open (@ "C: \ tempuploads \ newfile.txt", filemode. append );
Byte [] info = {(byte) 'h', (byte) 'E', (byte) 'l', (byte) 'l', (byte) 'o '};
Textfile. Write (Info, 0, info. Length );
Textfile. Close ();
}
(2) file creation method: file. Create ()
The statement of this method is as follows:
Public static filestream create (string path ;)
The following code demonstrates how to create a file named newfile.txt under c: \ tempuploads.
Because file. by default, the create method grants all users full read/write access to the new file. Therefore, the file is opened with the read/write access permission, which must be disabled before it can be opened by other applications. Therefore, you must use the close method of the filestream class to close the created file.
Private void makefile ()
{
Filestream newtext = file. Create (@ "C: \ tempuploads \ newfile.txt ");
Newtext. Close ();
}
(3) file deletion method: file. Delete ()
The method is declared as follows:
Public static void Delete (string path );
The following code deletes the newfile.txt file in the C: \ tempuploadsdirectory.
Private void deletefile ()
{
File. Delete (@ "C: \ tempuploads \ newfile.txt ");
}
(4) file copy method: file. Copy

The method is declared as follows:

Public static void copy (string sourcefilename, string destfilename, bool overwrite );
The following code copies c: \ tempuploads \ newfile.txt to c: \ tempuploads \ backup.txt.
The overwritegion of copetypes is set to true, so that if the backup.txt file already exists, it will be overwritten by the copied file.
Private void copyfile ()
{
File. Copy (@ "C: \ tempuploads \ newfile.txt", @ "C: \ tempuploads \ backup.txt", true );
}
(5) file movement method: file. Move
The method is declared as follows:
Public static void move (string sourcefilename, string destfilename );
The following code moves the backup.txt file under c: \ tempuploadsto the C root directory.
Note:
File Transfer can only be performed on the same logical disk. If you try to transfer files from drive C to drive D, an error will occur.
Private void movefile ()
{
File. Move (@ "C: \ tempuploads \ backup.txt", @ "C: \ backup.txt ");
}
(6) File Attribute setting method: file. setattributes
The method is declared as follows:
Public static void setattributes (string path, fileattributes );
The following code sets the properties of file c: \ tempuploads \ newfile.txt to read-only and hidden.
Private void setfile ()
{
File. setattributes (@ "C: \ tempuploads \ newfile.txt ",
Fileattributes. readonly | fileattributes. Hidden );
}
In addition to common read-only and hidden attributes, files include archive, system, and temporary. For details about file attributes, see the description of fileattributes in msdn.
(7) method for determining whether a file exists: file. exist
The method is declared as follows:
Public static bool exists (string path );
The following code checks whether the c: \ tempuploads \ newfile.txt file exists. If the file exists, copy the file first, delete it, and then move the copied file. If the file does not exist, create the file first, open the file, and write the file, finally, set the file attribute to read-only and hidden.
If (file. exists (@ "C: \ tempuploads \ newfile.txt") // checks whether the file exists.
{
Copyfile (); // copy a file
Deletefile (); // delete an object
Movefile (); // move the file
}
Else
{
Makefile (); // generate a file
Openfile (); // open the file
Setfile (); // set file attributes
}
In addition, the file class provides more support for text.
· Appendtext: append text to an existing file.
· Createtext: Creates or opens a new file for writing text.
· Opentext: open an existing text file for reading.
But the above method mainly on the UTF-8 encoding text operations, which is not flexible enough. We recommend that you use the following code to operate the TXT file.
· Read the TXT file. The sample code is as follows:
Streamreader txtreader = new streamreader (@ "C: \ tempuploads \ newfile.txt", system. Text. encoding. Default );
String filecontent;
Filecontent = txtreader. readend ();
Txtreader. Close ();
· Perform the "write" Operation on the TXT file. The sample code is as follows:
Streamwriter = new streamwrite (@ "C: \ tempuploads \ newfile.txt", system. Text. encoding. Default );
String filecontent;
Txtwriter. Write (filecontent );
Txtwriter. Close ();
System. Io. Directory and system. directoryinfo
It mainly provides various operations on directories. The system. Io namespace must be referenced during use. The following describes the main attributes and methods of a program instance.
(1) Directory Creation Method: directory. createdirectory
The method is declared as follows:
Public static directoryinfo createdirectory (string path );
The following code creates a directory named newdirectory in the C: \ tempuploads folder.
Private void makedirectory ()
{
Directory. createdirectory (@ "C: \ tempuploads \ newdirectoty ");
}
(2) Directory attribute setting method: directoryinfo. atttributes
The following code sets the c: \ tempuploads \ newdirectory directory to read-only and hidden. The directory attribute is set with fileattributes, which is the same as the file attribute.
Private void setdirectory ()
{
Directoryinfo newdirinfo = new directoryinfo (@ "C: \ tempuploads \ newdirectoty ");
Newdirinfo. atttributes = fileattributes. readonly | fileattributes. hidden;
}
(3) Directory deletion method: directory. Delete
The method is declared as follows:
Public static void Delete (string path, bool recursive );
The following code deletes the c: \ tempuploads \ Backup Directory. The second parameter of the delete method is of the bool type. It determines whether to delete non-empty directories. If the value of this parameter is true, the entire directory will be deleted, even if there are files or subdirectories under the Directory; if it is false, it can be deleted only when the directory is empty.
Private void deletedirectory ()
{
Directory. Delete (@ "C: \ tempuploads \ backup", true );
}
(4) Directory movement method: directory. Move
The method is declared as follows:
Public static void move (string sourcedirname, string destdirname );
The following code moves the directory c: \ tempuploads \ newdirectory to c: \ tempuploads \ backup.
Private void movedirectory ()
{
File. Move (@ "C: \ tempuploads \ newdirectory", @ "C: \ tempuploads \ backup ");
}
(5) obtain all subdirectories in the current directory: directory. getdirectories
The method is declared as follows:
Public static string [] getdirectories (string path ;);
The following code reads all the subdirectories in the C: \ tempuploads \ directory and stores them in a string array.
Private void getdirectory ()
{
String [] directorys;
Directorys = directory. getdirectories (@ "C: \ tempuploads ");
}
(6) method for obtaining all files in the current directory: directory. getfiles
The method is declared as follows:
Public static string [] getfiles (string path ;);
The following code reads all the files in the C: \ tempuploads \ directory and stores them in a string array.
Private void GetFile ()
{
String [] files;
Files = directory. getfiles (@ "C: \ tempuploads ",);
}
(7) method for determining whether a directory exists: directory. exist
The method is declared as follows:
Public static bool exists (
String path;
);
The following code checks whether the c: \ tempuploads \ newdirectory directory exists. If yes, first obtain the subdirectories and files in the directory, move them, and then delete the moved directories. If the directory does not exist, create the directory first, and set the Directory attribute to read-only and hidden.
If (file. exists (@ "C: \ tempuploads \ newdirectory") // you can check whether a directory exists.
{
Getdirectory (); // obtain sub-Directories
GetFile (); // get the object
Movedirectory (); // move the Directory
Deletedirectory (); // delete a directory
}
Else
{
Makedirectory (); // generate a directory
Setdirectory (); // Set Directory attributes
}
Note:
There are three methods of path: relative path under the current directory, relative path of the current work disk, and absolute path. Take c: \ TMP \ book as an example (assuming the current working directory is c: \ TMP ). "Book", "\ TMP \ book", and "C: \ TMP \ book" indicate c: \ TMP \ book.
In C #, "\" is a special character. To express it, use "\". This writing method is inconvenient, and the C # language provides @ to simplify it. You only need to add @ before the string to directly use "\". Therefore, the above path in C # should be represented as "book", @ "\ TMP \ book", @ "C: \ TMP \ book ".

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.