System. Io namespace

Source: Internet
Author: User

Use System. Io and Visual C #. Net to read text files

In Visual C #. net reading text files open and read files read access is a very important part of the input/output (IO) function, even if you do not need to write to the relevant file, so http://www.alixixi.com/Dev/Web/ASPNET/aspnet3/2007/2007050734418.html

Make sure that the project references at least the system namespace. Use the using statement for the system, system. Io, and system. Collections namespaces.CodeTo restrict the declarations in these namespaces. These statements must be prior to any other statement. Http://support.microsoft.com/kb/306777/zh-cn

1. Form and querystring collection objects

If a webpage uses the POST method to transmit data, use form to obtain the data (using a form or page, click the button to submit the data ):

Syntax: Request ("FILENAME ")

Request. Form ("FILENAME") (two options are available)

If the page has two or more texts with the same name, you must use the getvalues () method + index (serial number) to obtain them.

Syntax: request. Form. getvalues ("FILENAME") (INDEX)

Example: request. Form. getvalues ("username") (0)

Request. Form. getvalues ("username") (1)

If the webpage uses the get method to transmit data, use querystring to obtain data (parameters passed through the webpage ):

Syntax: Request ("FILENAME ")

Request. querystring ("FILENAME ")

If the page has two or more texts with the same name, you must use the getvalues () method + index (serial number) to obtain them.

Syntax: request. querystring. getvalues ("FILENAME") (INDEX)

Example: request. querystring. getvalues ("username") (0)

Request. querystring. getvalues ("username") (1)

2. Set the Chinese encoding (ASP. NET is a UTF-8 by default, you can set the Chinese encoding in the web. config configuration file)

<Configuration>

<System. Web>

<Globalization // This mark specifies the default encoding method and language

Fileencoding = "gb2312" // sets the encoding method.

Requestencoding = "gb2312" // sets the encoding method for the request object to obtain data.

Responseencoding = "gb2312" // encoding of data sent by the response object

Culture = "ZH-CN" // the language of the specified country. ZH-CN is China.

/>

</System. Web>

</Configuration>

3. Display disk Information

Driveinfo [] alldrives = driveinfo. getdrives ();

Foreach (driveinfo D in alldrives)

{

Response. Write ("drive:" + D. Name + "<br> ");

Response. Write ("file type:" + D. drivetype + "bytes <br> ");

If (D. isready = true)

{

Response. Write ("volume label:" + D. volumelabel + "<br> ");

Response. Write ("File System:" + D. driveformat + "<br> ");

Response. Write ("available space to current user:" + D. availablefreespace + "bytes <br> ");

Response. Write ("total available space:" + D. totalfreespace + "bytes <br> ");

Response. Write ("total size of drive:" + D. totalsize + "bytes <p> ");

}

}

4. Use Treeview to display local disks in two ways:

Treenode node = new treenode ("My Computer ");

This. treeview1.nodes. Add (node );

(1) driveinfo [] alldrives = driveinfo. getdrives ();

Foreach (driveinfo D in alldrives)

{

Treenode drivesnode = new treenode (D. Name + "*" + D. volumelabel + "*");

Node. childnodes. Add (drivesnode); // Add to Node

}

// D. volumelabel is the volume label of the corresponding Disk

(2) string [] STR = directory. getlogicaldrives ();

For (int K = 0; k <Str. length; k ++)

{

Treenode drivesnode = new treenode (STR [k]);

Node. childnodes. Add (drivesnode );

}

Or

Foreach (driveinfo K in Str)

{

Treenode drivesnode = new treenode (K. Name );

Node. childnodes. Add (drivesnode );

}

5. Display folders and files

Directoryinfo thisone = new directoryinfo ("disk"); // obtain the disk

Foreach (directoryinfo sub in thisone. getdirectories () // use the getdirectories () method to obtain the folder list

{

If (sub. getdirectories (). length> 0 | sub. getfiles (). length> 0)

{

Treenode subdirnode = new treenode (sub. Name );

Subdirnode. value = sub. fullname;

Drivesnode. childnodes. Add (subdirnode );

}

}

Foreach (fileinfo fi in thisone. getfiles ())

{

Treenode subnode = new treenode (Fi. Name );

Drivesnode. childnodes. Add (subnode );

}

6. UseProgramCreate a folder

Method 1 (dynamically create folders and subfolders)

String dir1 = "Images \" + pecode2; // defines the relative path (the folder name is pecode2)

String dir2 = "Images \" + pecode2 + "\" + penums2; // (create the folder penums2 in the folder above)

If (system. Io. Directory. exists (server. mappath (dir1) = false)

{

System. Io. Directory. createdirectory (server. mappath (dir1); // (if no parent is created, create a subfolder)

System. Io. Directory. createdirectory (server. mappath (dir2 ));

}

Else

{

System. Io. Directory. createdirectory (server. mappath (dir2); // (create a subfolder if it exists)

}

Method 2

Try

{

If (system. Io. Directory. exists (dir1 ))

{

Msglabel. Text = "this folder already exists ";

Return;

}

Else

{

System. Io. directoryinfo dirinfo = system. Io. Directory. createdirectory (dir1 );

Msglabel. Text = "this folder is created successfully! Creation Time: "+ system. Io. Directory. getcreationtime (dir1 );

}

}

Catch (exception ee)

{

Msglabel. Text = "processing failed! Cause of failure: "+ ee. tostring ();

}

7. delete folders and the following files

Public static void deletefolder (string DIR)

{

Foreach (string D in directory. getfilesystementries (DIR ))

{

If (file. exists (d ))

{

Fileinfo Fi = new fileinfo (d );

If (Fi. Attributes. tostring (). indexof ("readonly ")! =-1)

Fi. Attributes = fileattributes. normal;

File. Delete (d); // delete the file directly.

}

Else

Deletefolder (d); // recursively Delete subfolders

}

Directory. Delete (DIR); // delete an empty folder

}

Protected void button#click (Object sender, eventargs e) // call

{

Deletefolder ("F: \ 012 ");

}

8. Move the folder. (If the folder already exists, you can overwrite it or delete it before moving it)

The source folder and target folder must exist in the same hard disk partition. Otherwise, the Operation will fail.

(*** Failed! Cause of failure: system. Io. ioexception: The Source Path and target path must have the same root.

The move *** operation is invalid between volumes. In system. Io. Directory. Move (string sourcedirname, string destdirname)

In createdirectory. movebutton_click (Object sender, eventargs E ))

Method 1

String F1 = "d :\\ 013 ";

String F2 = "f :\\ 013 \ 011 ";

Try

{

If (! Directory. exists (F1 ))

{

Response. Write ("the source folder does not exist! ");

Return;

}

If (directory. exists (F2 ))

{

Response. Write ("the target folder already exists! ");

Return;

// Directory. Delete (F2); Delete and recreate

// Directory. Move (F1, F2 );

// Directory. Move (F1, F2 true); // Add true to overwrite the folder.

}

Directory. Move (F1, F2 );

Response. Write ("folder moved successfully! The source file has been removed. The target folder is "+ F2 );

}

Catch (exception ee)

{

Response. Write ("*** failed! Cause of failure: "+ ee. tostring ());

}

Method 2 (Writing Method)

Public bool mvdir (string frompath, string topath)

{

Try

{

If (! Directory. exists (topath ))

{

Directory. Move (frompath, topath );

Return true;

}

Else

{

Return false;

}

}

Catch (exception E)

{

Return false;

}

}

Protected void button#click (Object sender, eventargs E)

{

Mvdir ("F: \ 012", "F: \ 011 \ 012"); // call

}

9. File-related ***

String F1 = "d :\\ 013 \\ 2.txt ";

String F2 = "F: \ 011 \ 2.txt ";

If (! System. Io. file. exists (F2 ))

{

// System. Io. file. Copy (F1, F2); // copy the file

// File. Move (F1, F2); // move the file

File. Delete (F1, F2); // delete an object

}

Example:

// C # Write/read a text file

// Note: handle text garbled characters

Streamreader sr = new streamreader (filename, encoding. getencoding ("gb2312 "));

String filename = @ "C: I .txt ";

Streamreader sr = new streamreader (filename); string STR = Sr. Readline (); Sr. Close ();

Streamwriterrw = file. createtext (server. mappath (".") + "/mytext.txt ");

RW. writeline ("write ");

RW. writeline ("ABC ");

RW. writeline (". Net notes ");

RW. Flush ();

RW. Close ();

// Open a text file

Streamreadersr = file. opentext (server. mappath (".") + "/mytext.txt ");

Stringbuilderoutput = newstringbuilder ();

Stringrl;

While (RL = Sr. Readline ())! = NULL)

...{

Output. append (RL + "");

}

Lblfile. Text = output. tostring ();

Sr. Close ();

// C # append an object

Streamwritersw = 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

Stringorignfile, newfile;

Orignfile = server. mappath (".") + "/mytext.txt ";

Newfile = server. mappath (".") + "/mytextcopy.txt ";

File. Copy (orignfile, newfile, true );

// C # delete an object

Stringdelfile = server. mappath (".") + "/mytextcopy.txt ";

File. Delete (delfile );

// C # Move a file

Stringorignfile, newfile;

Orignfile = server. mappath (".") + "/mytext.txt ";

Newfile = server. mappath (".") + "/mytextcopy.txt ";

File. Move (orignfile, newfile );

// C # create a directory

// Create the directory c: sixage

Directoryinfod = directory. createdirectory ("C:/sixage ");

// D1 points to C: sixagesixage1

Directoryinfod1 = D. createsubdirectory ("sixage1 ");

// D2 points to C: sixagesixage1sixage1_1

Directoryinfod2 = d1.createsubdirectory ("sixage1_1 ");

// Set the current directory to C: sixage

Directory. setcurrentdirectory ("C:/sixage ");

// Create the directory c: sixagesixage2

Directory. createdirectory ("sixage2 ");

// Create the directory c: sixagesixage2sixage2_1

Directory. createdirectory ("sixage2/sixage2_1 ");

 

 

Reference: http://www.knowsky.com/398825.html

 

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.