C # input and output stream

Source: Internet
Author: User

   System.IO Namespaces for a. NET Framework class Library

The System.IO namespace contains types that allow you to read and write files and data streams, and types that provide basic file and directory support.
two C # file read and write FileStream detailed

1. (FileStream FS1 = File.Open ("C://test.txt", FileMode.Open));

FileMode.Open Open File C://test.txt directly with the FileStream class.

2. (FileStream FS2 = File.Open ("C://test.txt", Filemode.append, FileAccess.Write));

Filemode.append, open the file "C://test.txt" in an additional way, and write some content to "C://test.txt".

3. (FileStream fs3 =file.open ("C://test.txt", Filemode.truncate, FileAccess.ReadWrite, FileShare.Read)).

Filemode.truncate means to open and empty the file and then manipulate the file.

4. FileStream MyFileStream1 = new FileStream (@ "C:/testing.txt", FileMode.Create);

This means creating a file that can be read and written, and allowing others to read the contents of the file.

three C # stream-based input and output C # Stream-based input and output.: stream-is connected to a physical device through a C # I/O system, which is a physical storage device such as a hard disk to read and write. The methods and properties of the stream/stream are:

Method/properties Describe
void Close () Close the stream
void Flush () Clean up content in a stream
int ReadByte () Returns an integer representing the number of bytes entered, if no data is returned-1
int Read (byte[] buf,int offset, int numbytes)

NumBytes bytes read into byte[], starting at offset, returns the number of bytes read in successfully

Long Seek (long offset,seekorigin origin) Positions the current position at offset after origin as the initial position.
void WriteByte (Byte b) Writes a single byte to an output stream.
void Write (byte[] buf,int offset, int numbytes) NumBytes bytes written in byte[] buf starting with offset.
BOOL CanRead Whether it is readable
BOOL CanSeek Whether addressing is supported
BOOL CanWrite Whether data can be written
Long Length The length of the stream
Long Position The current position of the stream.

Three. The inheritance structure of the stream

Stream is a very large class, when reading and writing files, you can use different streams for professional data reading and writing.

A few rules of the FileMode and FileAccess:

Value Significance
FileMode.Create Create file, before the file with the same name will be destroyed
FileMode.CreateNew Create new file, this file does not exist before
FileMode.Open Open a file that already exists
FileMode.OpenOrCreate Open a file if it exists, otherwise create a new file
Filemode.truncate Open the file that exists to erase the contents of it
Filemode.append Writes data to the last file in the form of an append

If you want to restrict file access when you open a file, you can do this by constructing the following method:

FileStream (string filename, FileMode mode, FileAccess access);

FileName File mode operation mode

Access can be one of the following values: FileAccess.Read/fileaccess.write/FileAccess.ReadWrite; Filestreamfs=NewFileStream ("C://tab.txt ", filemode.openorcreate,fileaccess.read);The stream associated with post in C # and the byte array do not seem to be very informative. Here are the results of my research for the past few days. The feature is to generate b.jpg with a.jpg replication under the same folder. The code is as follows: ByteArray.aspx.csusingSystem;usingSystem.IO;usingSystem.Data;usingSystem.Drawing;usingSystem.Drawing.Imaging;usingSystem.Net;/*@Author: franksite:www.2solo.cndate:2008.02.20info:c# copy pictures, stream and ByteArray applications, generate picture parts*/namespaceBarray { Public Partial classImgHandler:System.Web.UI.Page {protected voidPage_Load (Objectsender, EventArgs e) {             Try{Stream sin=Page.Request.InputStream; System.Drawing.Image img=System.Drawing.Bitmap.FromStream (SIN); Bitmap BMP=NewBitmap (IMG); MemoryStream Bmpstream=NewMemoryStream (); Bmp.                 Save (Bmpstream, System.Drawing.Imaging.ImageFormat.Jpeg); FileStream FS=NewFileStream (System.Web.HttpContext.Current.Server.MapPath ("b.jpg"), FileMode.Create);                 Bmpstream.writeto (FS);                 Bmpstream.close (); Fs.                 Close ();                 Bmpstream.dispose (); Fs.                 Dispose (); Response.Write ("Success"); }             Catch{Response.Write ("failed"); } }}} Gopost.aspx.csusingSystem;usingSystem.IO;usingSystem.Drawing;usingSystem.Drawing.Imaging;usingSystem.Net;usingSystem.Text;/*@ author:franksite:www.2solo.cn date:2008.02.20info:c# copy picture, Stream and ByteArray app, submit picture section*/ namespacegopost{ Public Partial classPostHandler:System.Web.UI.Page {protected voidPage_Load (Objectsender, EventArgs e)         {postimage (); }       Private voidPostimage () {Try{HttpWebRequest request; stringImgurl = System.Web.HttpContext.Current.Server.MapPath ("a.jpg"); Request= (HttpWebRequest) httpwebrequest.create (http://localhost/bytearray/bytearray.aspx); Request. KeepAlive =true; Request. Method="POST"; byte[] ByteArray = Cvtimgbarr ((System.Drawing.Image)NewBitmap (@imgUrl), imageformat.jpeg); Request. ContentType="Image/jpeg"; Request. ContentLength=bytearray.length; Stream Newstream=request.                GetRequestStream (); Newstream.write (ByteArray,0, bytearray.length);                 Newstream.close (); Response.Write ("Copy Picture succeeded"); }             Catch{Response.Write ("failed to copy picture"); }        }        Private Static byte[] Cvtimgbarr (System.Drawing.Image imagetoconvert, ImageFormat formatofimage) {byte[] Imarr; Try             {                 using(MemoryStream myms =NewMemoryStream ())                    {Imagetoconvert.save (myms, formatofimage); Imarr=myms.                 ToArray (); }             }            Catch(Exception) {Throw; } returnImarr; }    } }

In contrast, the application of byte array in HTML forms may have been overlooked, but the correct application of byte array can greatly optimize the program and make some unexpected effects.

C # Stream andbyteconversion between []/*Conversion between------------------------------------------------------------------------  - - - */ /// <summary> ///turn the Stream into byte[]/// </summary>  Public byte[] Streamtobytes (Stream stream) {byte[] bytes =New byte[Stream.     Length]; Stream. Read (Bytes,0, Bytes.     Length); //sets the position of the current stream as the start of the streamStream. Seek (0, Seekorigin.begin); returnbytes;} /// <summary> ///turn byte[] into a Stream/// </summary>  PublicStream Bytestostream (byte[] bytes) {Stream Stream=NewMemoryStream (bytes); returnStream;} /*------------to------------ the conversion between Stream and file *--------------------------------------------- */ /// <summary> ///write Stream to file/// </summary>  Public voidStreamtofile (Stream stream,stringfileName) {     //convert Stream to byte[]    byte[] bytes =New byte[Stream.     Length]; Stream. Read (Bytes,0, Bytes.     Length); //sets the position of the current stream as the start of the streamStream. Seek (0, Seekorigin.begin); //write byte[] to fileFileStream fs =NewFileStream (FileName, FileMode.Create); BinaryWriter BW=NewBinaryWriter (FS); Bw.     Write (bytes); Bw.     Close (); Fs. Close (); } /// <summary> ///read Stream from File/// </summary>  PublicStream Filetostream (stringfileName) {                 //Open FileFileStream FileStream =NewFileStream (FileName, FileMode.Open, FileAccess.Read, FileShare.Read); //read the file byte[]    byte[] bytes =New byte[Filestream.length]; FileStream.Read (Bytes,0, Bytes.     Length);     Filestream.close (); //convert byte[] to StreamStream stream =NewMemoryStream (bytes); returnStream;} In addition, one application of XML is serialization, which is used to convert a string into a byte array by:byte[] bytes =System.Text.UTF8Encoding.UTF8.GetBytes (xmlcontent); In contrast, the method of converting a byte array to a string is:stringXmlcontent =System.Text.UTFEncoding.UTF8.GetString (bytes); From string to flow streambyte[] buffer = System.Text.Encoding.Unicode.GetBytes ("Faint"); MemoryStream Stream=NewMemoryStream (buffer); MemoryStream Ms=NewMemoryStream (System.Text.Encoding.Default.GetBytes (AOBJSTR));

C # input and output stream

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.