Csung operation hosts file (.txt)

Source: Internet
Author: User
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}

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.