Asp.net C # File Read text instance Function

Source: Internet
Author: User

Asp tutorial. net c # File Read text instance Function


The following code example reads the entire file and sends a notification when the end of the file is detected.
[C #]
Using system;
Using system. io;
Public class textfromfile {
Private const string file_name = "myfile.txt ";
Public static void main (string [] args ){
If (! File. exists (file_name )){
Console. writeline ("{0} does not exist! ", File_name );
Return;
}
Streamreader sr = file. opentext (file_name );
String input;
While (input = sr. readline ())! = Null ){
Console. writeline (input );
}
Console. writeline ("the end of the stream has been reached .");
Sr. close ();
}
}


This Code creates a streamreader pointing to myfile.txt by calling file. opentext. Streamreader. readline returns each row as a string. When there is no character to read, a message displays this situation and the stream is closed.

Write text to a file


The following code example creates a new text file and writes a string to it.
[C #]
Using system;
Using system. io;
Public class texttofile {
Private const string file_name = "myfile.txt ";
Public static void main (string [] args ){
If (file. exists (file_name )){
Console. writeline ("{0} already exists! ", File_name );
Return;
}
Streamwriter sr = file. createtext (file_name );
Sr. writeline ("this is my file .");
Sr. writeline ("I can write ints {0} or floats {1}, and so on .",
(1, 4.2 );
Sr. close ();
}
}

How to associate streamreader to filestream. The advantage is that you can explicitly specify whether to create a file and share a license. If you directly associate streamreader with a file, you cannot do this:
Filestream fs = new filestream (@ "c:" my documents "readme.txt ",
Filemode. open, fileaccess. read, fileshare. none );
Streamreader sr = new streamreader (fs );
In this example, specify streamreader to find the bytecode mark to determine which encoding method is used. In the following example, obtain streamreader from a fileinfo instance:
Fileinfo myfile = new fileinfo (@ "c:" my documents "readme.txt ");
Streamreader sr = myfile. opentext ();
Like filestream, streamreader should be disabled after use. If this is not done, the file will remain locked, so other processes cannot be executed (unless you use filestream to construct streamreader and specific fileshare. sharereadwrite ):
Sr. close ();
After instantiating streamreader, you can use this instance for some work. Like filestream, we only point out many methods that can be used to read data. You should check other infrequently used streamreader methods in the sdk documentation.
The simplest method used is readline (). This method reads a row at a time, but the returned string does not include the carriage return line break that marks the end of the row:
String nextline = sr. readline ();
In addition, you can extract all the remaining content of the file in a string (strictly speaking, it is all the remaining content of the stream ):
String restofstream = sr. readtoend ();
Only one character can be read:
Int nextchar = sr. read ();
The read () overload method can convert the returned characters into an integer. If it reaches the end of the stream,-1 is returned.
Finally, an offset value can be used to read the given number of characters into the array:
// To read 100 characters in.
Int nchars = 100;
Char [] chararray = new char [nchars];
Int ncharsread = sr. read (chararray, 0, nchars );
If you want to read more characters than the remaining characters in the file, ncharsread should be less than nchars.
2. streamwriter class
The streamwriter class works in a similar way as streamreader, but streamwriter can only be used to write files (or another stream ). The methods for constructing streamwriter include:
Streamwriter sw = new streamwriter (@ "c:" my documents ents "readme.txt ");
The above Code uses the utf8 encoding method.. net sets this encoding method as the default encoding method. If you want to specify other encoding methods:
Streamwriter sw = new streamwriter (@ "c:" my documents ents "readme.txt", true,
Encoding. ascii );
In this constructor, the second parameter is boolean, indicating whether the file should be opened in append mode. The constructor parameter cannot only be a file name and an encoding class.
Of course, you can associate streamwriter to a file stream to obtain more control options for opening a file:
Filestream fs = new filestream (@ "c:" my documents "readme.txt ",
Filemode. createnew, fileaccess. write, fileshare. read );
Streamwriter sw = new streamwriter (fs );
Fileinfo does not execute any method to return streamwriter.
In addition, if you want to create a new file and start writing data to it, you can use the following code:
Fileinfo myfile = new fileinfo (@ "c:" my documents "newfile.txt ");
Streamwriter sw = myfile. createtext ();
Like other stream classes, you must disable streamwriter after use:
Sw. close ();
You can use the four overload methods of streamwriter. write () to write a stream. The simplest way is to write a stream, followed by a carriage return line break:
String nextline = "groovy line ";
Sw. write (nextline );
You can also write one character:
Char nextchar = ~ A ~;
Sw. write (nextchar );
You can also write an array of characters:
Char [] chararray = new char [100];
// Initialize these characters
Sw. write (chararray );
You can even write part of the character array:
Int ncharstowrite = 50;
Int startatlocation = 25;
Char [] chararray = new char [100];
// Initialize these characters
Sw. write (chararray, startatlocation, ncharstowrite );
3. readwritetext example
The readwritetext example illustrates the usage of the streamreader and streamwriter classes. It is very similar to the preceding readbinaryfile example, but it is assumed that the file to be read is a text file and its content is displayed. It can also save files (including text modifications in the text box ). It saves files in unicode format.
The readwritetext shown in Figure 30-9 is used to display the previous newfile. aspx file. However, this read will be easier.
This section does not describe how to add event handlers to the open file dialog box, because they are basically the same as the preceding binaryfilereader example. As in this example, open a new file and call the displayfile () method. The only difference is the displayfile execution method. In this example, there is an option to save the file. This is represented by another menu item save. the handler of this option calls another method savefile ()(

Related Article

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.