This article summarizes two examples of reading text files. One is to read all the file content at a time and the other is to read the content by line. For more information, see.
First, add the using System. IO namespace.
Code Section:
| The Code is as follows: |
Copy code |
Public string readfile (string paths) { StreamReader sr = new StreamReader (Server. MapPath (paths), System. Text. Encoding. Default ); String input = sr. ReadToEnd (); Return input; } |
The above is the core code, and the complete file code is read.
| The Code is as follows: |
Copy code |
Using System; Using System. Collections; Using System. Configuration; Using System. Data; Using System. Linq; Using System. Web; Using System. Web. Security; Using System. Web. UI; Using System. Web. UI. HtmlControls; Using System. Web. UI. WebControls; Using System. Web. UI. WebControls. WebParts; Using System. Xml. Linq; Using System. IO; Namespace test { Public partial class Text: System. Web. UI. Page { Protected void Page_Load (object sender, EventArgs e) { Response. Write (GetInterIDList ("asp.txt ")); } // Read the contents of the txt file Public string GetInterIDList (string strfile) { String strout; Strout = ""; If (! File. Exists (System. Web. HttpContext. Current. Server. MapPath (strfile ))) { } Else { StreamReader sr = new StreamReader (System. Web. HttpContext. Current. Server. MapPath (strfile), System. Text. Encoding. Default ); String input = sr. ReadToEnd (); Sr. Close (); Strout = input; } Return strout; } } } |
One row reads the current file
Example
| The Code is as follows: |
Copy code |
Using System; Using System. Data; Using System. Configuration; Using System. Web; Using System. Web. Security; Using System. Web. UI; Using System. Web. UI. WebControls; Using System. Web. UI. WebControls. WebParts; Using System. Web. UI. HtmlControls; Using System. IO; Using System. Text; Public partial class _ Default: System. Web. UI. Page { Protected void Page_Load (object sender, EventArgs e) { If (! This. IsPostBack) { String Path = Server. MapPath ("4.txt "); InsertStr (Path ); } } Public void insertStr (string Path) { String strLine = ""; Int I = 0; Try { StreamReader sr = new StreamReader (Path, Encoding. GetEncoding ("GB2312 ")); StrLine = sr. ReadLine (); While (strLine! = Null) { Response. Write (strLine + "<br> "); StrLine = sr. ReadLine (); I ++; } Response. Write (I ); Sr. Dispose (); Sr. Close (); } Catch { } }
} |