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 );
}
}
1. Read text files
1/** // <summary>
2 // read text files
3 /// </summary>
4 private void ReadFromTxtFile ()
5 {
6 if (filePath. PostedFile. FileName! = "")
7 {
8 txtFilePath = filePath. PostedFile. FileName;
9 fileExtName = txtFilePath. Substring (txtFilePath. LastIndexOf (".") + 1, 3 );
10
11 if (fileExtName! = "Txt" & fileExtName! = "TXT ")
12 {
13 Response. Write ("select a text file ");
14}
15 else
16 {
17 StreamReader fileStream = new StreamReader (txtFilePath, Encoding. Default );
18 txtContent. Text = fileStream. ReadToEnd ();
19 fileStream. Close ();
20}
21}
22}
2. Get the file list
1/** // <summary>
2 // obtain the file list
3 /// </summary>
4 private void GetFileList ()
5 {
6 string strCurDir, FileName, FileExt;
7
8/** // File Size
9 long FileSize;
10
11/*** // The last modification time;
12 DateTime FileModify;
13
14/** // Initialization
15 if (! IsPostBack)
16 {
17/*** // The default directory of the current page during initialization
18 strCurDir = Server. MapPath (".");
19 lblCurDir. Text = strCurDir;
20 txtCurDir. Text = strCurDir;
21}
22 else
23 {
24 strCurDir = txtCurDir. Text;
25 txtCurDir. Text = strCurDir;
26 lblCurDir. Text = strCurDir;
27}
28 FileInfo fi;
29 DirectoryInfo dir;
30 TableCell td;
31 TableRow tr;
32 tr = new TableRow ();
33
34/*** // Add cell content dynamically
35 td = new TableCell ();
36 td. Controls. Add (new LiteralControl ("file name "));
37 tr. Cells. Add (td );
38 td = new TableCell ();
39 td. Controls. Add (new LiteralControl ("file type "));
40 tr. Cells. Add (td );
41 td = new TableCell ();
42 td. Controls. Add (new LiteralControl ("file size "));
43 tr. Cells. Add (td );
44 td = new TableCell ();
45 td. Controls. Add (new LiteralControl ("Last modified "));
46 tr. Cells. Add (td );
47
48 tableDirInfo. Rows. Add (tr );
49
50/*** // create a directory reference object for the current directory
51 DirectoryInfo dirInfo = new DirectoryInfo (txtCurDir. Text );
52
53/*** // cyclically determine the files and directories under the current directory
54 foreach (FileSystemInfo fsi in dirInfo. GetFileSystemInfos ())
55 {
56 FileName = "";
57 FileExt = "";
58 FileSize = 0;
59
60/*** // if the file is
61 if (fsi is FileInfo)
62 {
63 fi = (FileInfo) fsi;
64
65/*** // get the file name
66 FileName = fi. Name;
67
68/*** // get the file extension
69 FileExt = fi. Extension;
70
71/*** // obtain the file size
72 FileSize = fi. Length;
73
74/** // obtain the last modification time of the file
75 FileModify = fi. LastWriteTime;
76}
77
78/** // otherwise it is a directory
79 else
80 {
81 dir = (DirectoryInfo) fsi;
82
83/*** // obtain the directory name
84 FileName = dir. Name;
85
86/*** // get the last modification time of the Directory
87 FileModify = dir. LastWriteTime;
88
89/*** // set the file extension to "folder"
90 FileExt = "folder ";
91}
92
93/*** // Add Table content dynamically
94 tr = new TableRow ();
95 td = new TableCell ();
96 td. Controls. Add (new LiteralControl (FileName ));
97 tr. Cells. Add (td );
98 td = new TableCell ();
99 td. Controls. Add (new LiteralControl (FileExt ));
100 tr. Cells. Add (td );
101 td = new TableCell ();
102 td. Controls. Add (new LiteralControl (FileSize. ToString () + "Byte "));
103 tr. Cells. Add (td );
104 td = new TableCell ();
105 td. Controls. Add (new LiteralControl (FileModify. ToString ("yyyy-mm-dd hh: mm: ss ")));
106 tr. Cells. Add (td );
107 tableDirInfo. Rows. Add (tr );
108}
109}
3. Read log files
1/** // <summary>
2 // read the log file
3 /// </summary>
4 private void ReadLogFile ()
5 {
6/** // read log files from the specified directory in the form of opening or creating
7 FileStream fs = new FileStream (Server. MapPath ("upedFile") + "\ logfile.txt", FileMode. OpenOrCreate, FileAccess. Read );
8
9/*** // define the output string
10 StringBuilder output = new StringBuilder ();
11
12/*** // initialize the string with a length of 0
13 output. Length = 0;
14
15/*** // create a read data stream for the file stream created above
16 StreamReader read = new StreamReader (fs );
17
18/*** // set the starting position of the current stream to the starting point of the file stream
19 read. BaseStream. Seek (0, SeekOrigin. Begin );
20
21/*** // read the file
22 while (read. Peek ()>-1)
23 {
24/*** // get a line of content and wrap it
25 output. Append (read. ReadLine () + "\ n ");
26}
27
28/*** // close and release the read data stream
29 read. Close ();
30
31/*** // return the log file content
32 return output. ToString ();
33}
4. Write log files
1/** // <summary>
2 // write the log file
3 /// </summary>
4 /// <param name = "input"> </param>
5 private void WriteLogFile (string input)
6 {
7/*** // specify the directory of the log file
8 string fname = Server. MapPath ("upedFile") + "\ logfile.txt ";
9/*** // defines the object of File Information
10 FileInfo finfo = new FileInfo (fname );
11
12/*** // determine whether the file exists and whether it is greater than 2 K
13 if (finfo. Exists & finfo. Length> 2048)
14 {
15/*** // delete the file
16 finfo. Delete ();
17}
18/*** // create a file-only stream
19 using (FileStream fs = finfo. OpenWrite ())
20 {
21/*** // create a write data stream based on the file stream created above
22 StreamWriter w = new StreamWriter (fs );
23
24/*** // set the start position of the write data stream to the end of the file stream
25 w. BaseStream. Seek (0, SeekOrigin. End );
26
27/*** // write "Log Entry :"
28 w. Write ("\ nLog Entry :");
29
30/*** // write the current system time and line feed
31 w. Write ("{0} {1} \ r \ n", DateTime. Now. ToLongTimeString (),
32 DateTime. Now. ToLongDateString ());
33
34/*** // write the log Content and line feed
35 w. Write (input + "\ n ");
36
37/** // write ---------------------------------------------- "and wrap
38 w. Write ("------------------------------------ \ n ");
39
40/*** // clear the buffer content and write the buffer content to the base stream
41 w. Flush ();
42
43/*** // close the write data stream
44 w. Close ();
45}
46}
5. Create an HTML file
1/** // <summary>
2 // create an HTML file
3 /// </summary>
4 private void CreateHtmlFile ()
5 {
6/** // defines an array with the same number of html tags
7 string [] newContent = new string [5];
8 StringBuilder strhtml = new StringBuilder ();
9 try
10 {
11/*** // create a StreamReader object
12 using (StreamReader sr = new StreamReader (Server. MapPath ("createHTML") + "\ template.html "))
13 {
14 String oneline;
15
16/*** // read the specified HTML file template
17 while (oneline = sr. ReadLine ())! = Null)
18 {
19 strhtml. Append (oneline );
20}
21 sr. Close ();
22}
23}
24 catch (Exception err)
25 {
26/*** // output exception information
27 Response. Write (err. ToString ());
28}
29/*** // assign values to the marked Array
30 newContent [0] = txtTitle. Text; // Title
31 newContent [1] = "BackColor = '# cccfff'"; // background color
32 newContent [2] = "# ff0000"; // font color
33 newContent [3] = "100px"; // font size
34 newContent [4] = txtContent. Text; // Main Content
35
36/*** // generate an html file based on the new content above
37 try
38 {
39/*** // specify the HTML file to be generated
40 string fname = Server. MapPath ("createHTML") + "\" + DateTime. Now. ToString ("yyyymmddhhmmss") + ". html ";
41
42/*** // Replace the html template file with the new content
43 for (int I = 0; I <5; I ++)
44 {
45 strhtml. Replace ("$ htmlkey [" + I + "]", newContent [I]);
46}
47/*** // create a file information object
48 FileInfo finfo = new FileInfo (fname );
49
50/*** // create a file stream in the form of opening or writing
51 using (FileStream fs = finfo. OpenWrite ())
52 {
53/*** // create a write data stream based on the file stream created above
54 StreamWriter sw = new StreamWriter (fs, System. Text. Encoding. GetEncoding ("GB2312 "));
55
56/*** // write the new content to the created HTML page
57 sw. WriteLine (strhtml );
58 sw. Flush ();
59 sw. Close ();
60}
61
62/*** // set the hyperlink attributes
63 hyCreateFile. Text = DateTime. Now. ToString ("yyyymmddhhmmss") + ". html ";
64 hyCreateFile. NavigateUrl = "createHTML/" + DateTime. Now. ToString ("yyyymmddhhmmss") + ". html ";
65}
66 catch (Exception err)
67 {
68 Response. Write (err. ToString ());
69}
70}
For more information, see
1: http://msdn.microsoft.com/library/chs/default.asp? Url =/library/CHS/cpref/html/frlrfsystemiodirectoryinfoclasstopic. asp
2: http://www.clys.net/bbs/forum_posts.asp? TID = 87 & PN = 1 & get = last