1. Create a text file
Public class FileClass
{
Public static void Main ()
{
WriteToFile ();
}
Static void WriteToFile ()
{
StreamWriter SW;
SW = File. CreateText (@ "c: MyTextFile.txt ");
SW. WriteLine ("God is greatest of them all ");
SW. WriteLine ("This is second line ");
SW. Close ();
Console. WriteLine ("File Created SucacessFully ");
}
}
2. Read files
Public class FileClass
{
Public static void Main ()
{
ReadFromFile (@ "c: MyTextFile.txt ");
}
Static void ReadFromFile (string filename)
{
StreamReader SR;
String S;
SR = File. OpenText (filename );
S = SR. ReadLine ();
While (S! = Null)
{
Console. WriteLine (S );
S = SR. ReadLine ();
}
SR. Close ();
}
}
Public class FileClass
{
Public static void Main ()
{
AppendToFile ();
}
Static void AppendToFile ()
{
StreamWriter SW;
SW = File. AppendText (@ "C: MyTextFile.txt ");
SW. WriteLine ("This Line Is Appended ");
SW. Close ();
Console. WriteLine ("Text Appended Successfully ");
}
}
3. append operations
C # append an object
StreamWriter sw = File. AppendText (Server. MapPath (".") + "\ myText.txt ");
Sw. WriteLine ("Chasing ideals ");
Sw. WriteLine ("kzlll ");
Sw. WriteLine (". NET notes ");
Sw. Flush ();
Sw. Close ();
C # copy an object
String OrignFile, NewFile;
OrignFile = Server. MapPath (".") + "\ myText.txt ";
NewFile = Server. MapPath (".") + "\ myTextCopy.txt ";
File. Copy (OrignFile, NewFile, true );
C # delete an object
String delFile = Server. MapPath (".") + "\ myTextCopy.txt ";
File. Delete (delFile );
C # Move files
String OrignFile, NewFile;
OrignFile = Server. MapPath (".") + "\ myText.txt ";
NewFile = Server. MapPath (".") + "\ myTextCopy.txt ";
File. Move (OrignFile, NewFile );
C # create a directory
// Create the directory c: \ sixAge
DirectoryInfo d = Directory. CreateDirectory ("c: \ sixAge ");
// D1 points to c: \ sixAge \ sixAge1
DirectoryInfo d1 = d. CreateSubdirectory ("sixAge1 ");
// D2 points to c: \ sixAge \ sixAge1 \ sixAge1_1
DirectoryInfo d2 = d1.CreateSubdirectory ("sixAge1_1 ");
// Set the current directory to c: \ sixAge
Directory. SetCurrentDirectory ("c: \ sixAge ");
// Create the directory c: \ sixAge \ sixAge2
Directory. CreateDirectory ("sixAge2 ");
// Create the directory c: \ sixAge \ sixAge2 \ sixAge2_1
Directory. CreateDirectory ("sixAge2 \ sixAge2_1 ");
Recursively delete folders and files
<% @ Page Language = C # %>
<% @ Import namespace = "System. IO" %>
<Script runat = server>
Public void DeleteFolder (string dir)
{
If (Directory. Exists (dir) // if this folder Exists, delete it
{
Foreach (string d in Directory. GetFileSystemEntries (dir ))
{
If (File. Exists (d ))
File. Delete (d); // Delete the File directly.
Else
DeleteFolder (d); // recursively Delete subfolders
}
Directory. Delete (dir); // Delete an empty folder
Response. Write (dir + "folder deleted successfully ");
}
Else
Response. Write (dir + "this folder does not exist"); // If the folder does not exist, a prompt is displayed.
}
Protected void Page_Load (Object sender, EventArgs e)
{
String Dir = "D :\\ gbook \ 11 ";
DeleteFolder (Dir); // call the function to delete a folder
}
// ================================================ ======================
// Implement a static method to copy all the content in the specified folder to the target folder
// If the target folder is read-only, an error is returned.
// April 18April2005 In STU
// ================================================ ======================
Public static void CopyDir (string srcPath, string aimPath)
{
Try
{
// Check whether the target directory ends with a directory delimiter. If not, add it.
If (aimPath [aimPath. Length-1]! = Path. DirectorySeparatorChar)
AimPath + = Path. DirectorySeparatorChar;
// Determine whether the target directory exists. If it does not exist, create it.
If (! Directory. Exists (aimPath) Directory. CreateDirectory (aimPath );
// Obtain the file list of the source Directory, which is an array containing the file and directory path
// Use the following method if you direct to the file under the copy target file without including the Directory
// String [] fileList = Directory. GetFiles (srcPath );
String [] fileList = Directory. GetFileSystemEntries (srcPath );
// Traverse all files and directories
Foreach (string file in fileList)
{
// Process the file as a directory first. If this directory exists, recursively Copy the file under this directory.
If (Directory. Exists (file ))
CopyDir (file, aimPath + Path. GetFileName (file ));
// Otherwise, Copy the file directly.
Else
File. Copy (file, aimPath + Path. GetFileName (file), true );
}
}
Catch (Exception e)
{
MessageBox. Show (e. ToString ());
}
}
// ================================================ ======================
// Implement a static method to Detele all content in the specified folder
// Perform the test with caution. The operation cannot be restored after deletion.
// April 18April2005 In STU
// ================================================ ======================
Public static void DeleteDir (string aimPath)
{
Try
{
// Check whether the target directory ends with a directory delimiter. If not, add it.
If (aimPath [aimPath. Length-1]! = Path. DirectorySeparatorChar)
AimPath + = Path. DirectorySeparatorChar;
// Obtain the file list of the source Directory, which is an array containing the file and directory path
// Use the following method if you direct to the file under the Delete target file without including the Directory
// String [] fileList = Directory. GetFiles (aimPath );
String [] fileList = Directory. GetFileSystemEntries (aimPath );
// Traverse all files and directories
Foreach (string file in fileList)
{
// Process the file as a directory first. If this directory exists, recursively Delete the files under this directory.
If (Directory. Exists (file ))
{
DeleteDir (aimPath + Path. GetFileName (file ));
}
// Otherwise, Delete the file directly.
Else
{
File. Delete (aimPath + Path. GetFileName (file ));
}
}
// Delete a folder
System. IO. Directory. Delete (aimPath, true );
}
Catch (Exception e)
{
MessageBox. Show (e. ToString ());
}
}
Namespace to be referenced:
Using System. IO;
/** // <Summary>
/// Copy a folder (including subfolders) to the specified folder. Both the source folder and the target folder must be in the absolute path. Format: CopyFolder (source folder, target folder );
/// </Summary>
/// <Param name = "strFromPath"> </param>
/// <Param name = "strToPath"> </param>
//--------------------------------------------------
// Prepared by: Go to dinner tomorrow QQ: 305725744
//---------------------------------------------------
Public static void CopyFolder (string strFromPath, string strToPath)
{
// If the source folder does not exist, create
If (! Directory. Exists (strFromPath ))
{
Directory. CreateDirectory (strFromPath );
}
// Obtain the name of the folder to be copied
String strFolderName = strFromPath. Substring (strFromPath. LastIndexOf ("\") + 1, strFromPath. Length-strFromPath. LastIndexOf ("\")-1 );
// If no source folder exists in the target folder, create the source folder in the target folder.
If (! Directory. Exists (strToPath + "\" + strFolderName ))
{
Directory. CreateDirectory (strToPath + "\" + strFolderName );
}
// Create an array to save the file name in the source folder
String [] strFiles = Directory. GetFiles (strFromPath );
// Copy objects cyclically
For (int I = 0; I <strFiles. Length; I ++)
{
// Get the copied file name. Only the file name is taken and the address is truncated.
String strFileName = strFiles [I]. substring (strFiles [I]. lastIndexOf ("\") + 1, strFiles [I]. length-strFiles [I]. lastIndexOf ("\")-1 );
// Start copying an object. true indicates overwriting an object of the same name.
File. Copy (strFiles [I], strToPath + "\" + strFolderName + "\" + strFileName, true );
}
// Create a DirectoryInfo instance
DirectoryInfo dirInfo = new DirectoryInfo (strFromPath );
// Obtain the names of all subfolders in the source folder
DirectoryInfo [] ZiPath = dirInfo. GetDirectories ();
For (int j = 0; j <ZiPath. Length; j ++)
{
// Obtain the names of all subfolders
String strZiPath = strFromPath + "\" + ZiPath [j]. ToString ();
// Use the obtained subfolder as the new source folder and start a new round of copying from the beginning
CopyFolder (strZiPath, strToPath + "\" + strFolderName );
}
}
Analysis on file operations in C #
Release date: 2003.02.13 Source: Saidi Author: Wang kiming
Microsoft's. Net Framework provides us with stream-based I/O operations, which greatly simplifies developers' work. Because we can operate on a series of common objects, we don't have to worry about whether the I/O operation is related to local files or network data .. The Net Framework mainly provides a System. IO namespace, which basically contains all classes related to I/O operations.
This article will introduce some basic file operations, including directory and file operations in the file system, as well as file read/write operations. By using System. IO. directoryInfo and System. IO. the FileInfo class allows you to easily perform operations related to directories and files. IO. streamReader class and System. IO. streamWriter class allows you to conveniently perform operations related to file read/write.
Namespace Overview
The following table shows the most important classes in the System. IO namespace. By using these classes, we can complete basic file operations.
Table 1
Class Name
Functions and usage
BinaryReader and BinaryWriter
Read/write binary data
Directory, File, DirectoryInfo, and FileInfo
Creates, deletes, and moves directories and files, and obtains information about specific directories and files through attributes.
FileStream
Access files in random mode
MemoryStream
Access data stored in memory
StreamReader and StreamWriter
Read/write text data
StringReader, StringWriter
Read and Write text data using string Buffering
Use the DirectoryInfo class and FileInfo class
The base classes of the DirectoryInfo and FileInfo classes are both FileSystemInfo classes. This class is an abstract class. That is to say, you cannot instantiate this class. You can only generate and instantiate its subclass by inheriting it. However, you can use the attributes defined by the class. The following table shows the attributes defined by the class.
Table 2
Attribute
Functions and usage
Attributes
Returns file-related attribute values, which use the FileAttributes Enumeration type values.
CreationTime
Returns the file creation time.
Exists
Check whether the file exists in the specified directory
Extension
Returns the file extension.
LastAccessTime
Returns the last Object Access time.
FullName
Absolute path of the returned File
LastWriteTime
Returns the last write operation time of the object.
Name
Returns the name of the specified file.
Delete ()
Delete an object with caution.
The DirectoryInfo class provides methods for creating, deleting, and moving directories. To use various attributes in Table 2, we must first create a DirectoryInfo class object and then access its various attributes.
DirectoryInfo dir1 = new DirectoryInfo (@ "F: \ Test ");
Console. WriteLine ("Full Name is: {0}", dir1.FullName );
Console. WriteLine ("Attributes are: {0}", dir1.Attributes. ToString ());
At the same time, we can also use the FileAttributes Enumeration type value to obtain various file-related attributes. The following table shows the values of this enumeration type.
Table 3
Value
Functions and usage
Archive
Returns the archiving status of an object.
Compressed
Whether the returned file is compressed
Directory
Whether the returned file is a directory
Encrypted
Whether the returned file is encrypted
Hidden
Whether the returned file is hidden
Offline
Indicates that file data is not available.
ReadOnly
Indicates that the file is read-only.
System
Indicates that the file is a system file
File Operations under the Directory
Using the DirectoryInfo class object, we can easily perform operations on directories and files in directories. If you want to obtain all BMP files in a directory F: \ Pictures, the following code can be used to implement this function.
DirectoryInfo dir = new DirectoryInfo (@ "F: \ Pictures ");
FileInfo [] bmp files = dir. GetFiles ("*. bmp );
Console. WriteLine ("Total number of bmp files", bmp files. Length );
Foreach (FileInfo f in BMP files)
{
Console. WriteLine ("Name is: {0}", f. Name );
Console. WriteLine ("Length of the file is: {0}", f. Length );
Console. WriteLine ("Creation time is: {0}", f. CreationTime );
Console. WriteLine ("Attributes of the file are: {0 }",
F. Attributes. ToString ());
}
In the above Code, we first create a DirectoryInfo object, and then call the GetFiles method of this object to obtain all files with the bmp extension under the directory F: \ Pictures, the value returned by this method is a FileInfo array, and each element represents a file. Finally, the program lists the relevant attributes of each BMP file.
Create subdirectory
It is very easy to use the DirectoryInfo class to create sub-directories. You only need to call the CreateSubdirectory () method. The Demo code is as follows.
DirectoryInfo dir = new DirectoryInfo (@ "F: \ Pictures ");
Try
{
Dir. CreateSubdirectory ("Sub ");
Dir. CreateSubdirectory (@ "Sub \ MySub ");
}
Catch (IOException e)
{
Console. WriteLine (e. Message );
}
Use the FileInfo class to create and delete files
Through the FileInfo class, we can easily create a file, access the file attributes, and perform basic operations on the file, such as opening the file, closing the file, and reading and writing the file. The following code shows how to create a text file and access the file information such as its creation time, the absolute path of the file, and the file attributes. Finally, the program provides a method to delete the file.
FileInfo fi = new FileInfo (@ "F: \ Myprogram.txt ");
FileStream fs = fi. Create ();
Console. WriteLine ("Creation Time: {0}", fi. CreationTime );
Console. WriteLine ("Full Name: {0}", fi. FullName );
Console. WriteLine ("FileAttributes: {0}", fi. Attributes. ToString ());
Console. WriteLine ("Press any key to delete the file ");
Console. Read ();
Fstr. Close ();
Fi. Delete ();
Understanding the Open () method of the FileInfo class
We must Open the file before performing read/write operations on the file. The FileInfo class provides us with an Open () method that contains two Enumeration type values, one is the FileMode Enumeration type value, and the other is the FileAccess Enumeration type value. By setting these two parameter values, we can control the file access mode and operation permissions. The following two tables show the values of the FileMode Enumeration type and the FileAccess Enumeration type respectively.
Table 4
Value
Functions and usage
Append
Open the file and add data. When this method is used, the FileAccess Enumeration type value should be Write.
Create
Creating a new file may overwrite existing files.
CreateNew
Create a new file. If the file already exists, an IOException is thrown.
Open
Open an existing file.
OpenOrCreate
Open the file. If the file does not exist, create it.
Truncate
Truncates an existing file.
Table 5
Value
Functions and usage
Read
Data can be read from a file.
ReadWrite
You can read data from a file and write data to the file.
Write
You can write data to a file.
The following code shows how to use the Open () method.
FileInfo f = new FileInfo ("F: \ MyFile.txt ");
FileStream s = f. Open (FileMode. OpenorWrite, FileAccess. Read );
Use the StreamReader and StreamWriter classes to read and write files.
Read/write operations on files should be the most important file operation, System. the IO namespace provides many file read/write operations. Here I want to introduce the most common and basic StreamReader and StreamWriter classes. From the names of these two classes, we can easily find that they are both stream-based read/write operation classes.
We can use the OpenText () method of the File class to obtain a StreamReader object. With this object, we can perform read operations on text files by using the following methods:
Console. WriteLine ("Reading the contents from the file ");
StreamReader s = File. OpenText ("MyText.txt ");
String read = null;
While (read = s. ReadLine ())! = Null)
{
Console. WriteLine (read );
}
S. Close ();
By calling the CreateText () method of the FileInfo class, we can obtain a StreamWriter object. by calling the WriteLine () method of the StreamWriter class, we can write data to the text file. The method is as follows:
FileInfo f = new FileInfo ("MyText.txt ")
StreamWriter w = f. CreateText ();
W. WriteLine ("This is from ");
W. WriteLine ("Chapter 1 ");
W. WriteLine ("Of C # Module ");
W. Write (w. NewLine );
W. WriteLine ("Thanks for your time ");
W. Close ();
Summary
I briefly introduced the basic knowledge and methods of C # file operations. Through this article, you can easily find the convenience of I/O operations under the. Net Framework. After learning this article, if you want to perform some basic file operations. i/O namespaces such as the DirectoryInfo, FileInfo, FileStream, StreamReader, and StreamWriter classes must have a basic understanding and be used flexibly in practical applications. If you want to further control file operations, you may want to study the more specific and detailed classes in the System. IO namespace. Finally, I hope this article will help you.
From the column csh624385188