Read and write files using FileStream objects

Source: Internet
Author: User
Tags try catch

In the project development often involves to read and write to the file, C # provides many ways to read and write to the file, today said FileStream object.
FileStream represents a stream that points to a file on a disk or network path. General operations files are used to StreamReader and StreamWriter because they manipulate character data. Instead, the FileStream object operates on a byte and byte array. Some operations must be performed using the FileStream object, such as randomly accessing data at a point in the middle of a file.
There are many different ways to create FileStream objects, which are created using file names and FileMode enumeration values:
One, read the file, remember to refer to the System.IO namespace:

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.IO;namespaceconsoleapplicationtest{classProgram {Static voidMain (string[] args) {            //create a byte array and a character array for the data you want to read            byte[] Bytedata =New byte[ $]; Char[] Chardata =New Char[ $]; //Catch Exception: Easy exception when manipulating files, preferably with try CatchFileStream file =NULL; Try            {                //opens a current Program.cs file, at which point a pointer to a read-write file (or an action cursor) points to the beginning of the fileFile =NewFileStream (@".. \.. \program.cs", FileMode.Open); //read-write pointer moves backward 10 bytes from the beginningFile. Seek (Ten, Seekorigin.begin); //reads 200 bytes of data into a byte array from the position of the current read-write pointerFile. Read (Bytedata,0, $); }Catch(Exception e) {Console.WriteLine ("Read File exception: {0}", E); }            finally            {                //Close File Stream                if(File! =NULL) file.            Close (); }            //Create an Encoding converter decoderDecoder Decoder =Encoding.UTF8.GetDecoder (); //convert a byte array to a character arrayDecoder. GetChars (Bytedata,0, $, Chardata,0);            Console.WriteLine (Chardata);        Console.readkey (); }}}

The results appear as follows:

Second, write the file:

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.IO;namespaceconsoleapplicationtest{classProgram {Static voidMain (string[] args) {            byte[] bytedata; Char[] chardata; FileStream file=NULL; Try            {                //Create a Aa.txt file under the current startup directoryFile =NewFileStream ("Aa.txt", FileMode.Create); //Convert "Test write text to file" into a character array and put it into chardataChardata ="Test Write text to file".                ToCharArray (); Bytedata=New byte[Chardata.length]; //Create an encoder to convert characters to bytesEncoder Encoder =Encoding.UTF8.GetEncoder (); Encoder. GetBytes (Chardata,0, Chardata.length, Bytedata,0,true); File. Seek (0, Seekorigin.begin); //writing data to a fileFile. Write (Bytedata,0, bytedata.length); }Catch(Exception e) {Console.WriteLine ("Write file exception: {0}", E); }            finally            {                if(File! =NULL) file.            Close ();        } console.readkey (); }    }}

The results are as follows:

Read and write files using FileStream objects

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.