The difference between FileStream and Streamwriter/streamreader in C #

Source: Internet
Author: User
Tags throw exception

Thank you first! Turn from: http://blog.sina.com.cn/s/blog_67299aec0100snk4.html This may not be very deep, but it is clear that the FileStream object represents a stream that points to a file on a disk or network path. This class provides a way to read and write bytes in a file , but often uses StreamReader or StreamWriter to perform these functions. This is becauseThe FileStream class operates on byte and byte arrays, while the Stream class operates on character data. This is an important difference between these two types, if you are ready to read the byte data, read it with StreamReader and then use System.Text.Encoding.Default.GetBytes conversion, if the following, there may be data loss, such as the number of byte data is not correct. So use FileStream when manipulating byte data。 String textcontent = Filestream.readtoend (); byte[] bytes = System.Text.Encoding.Default.GetBytes (textcontent); Character data is easy to use, but some operations, such as random file access (accessing data at a point in the middle of a file), must be performed by the FileStream object.
The simplest constructor for creating a FileStream object is as follows:
FileStream file = new FileStream (filename,filemode.member);// default mode, readable and writable
FileStream file = new FileStream (FileName, Filemode.member, Fileaccess.member);
And the members of FileAccess:

Members

Description

Read

Open file for read-only

Write

Open file for write-only

ReadWrite

Open file for read-write

The action specified on the file not FileAccess enumeration member causes an exception to be thrown. The purpose of this property is to change the user's access to the file based on the user's level of authentication.

In a version of the FileStream constructor that does not use the FileAccess enumeration parameter, the default value FileAccess is used. ReadWrite.

FileMode enumeration members, what happens with each value, depends on whether the specified file name represents the existing files.

Members

File exists

File does not exist

Append

Opens the file, flows to the end of the file, and can only be used in conjunction with enumeration FileAccess.Write

Create a new file. Can only be used in conjunction with enumeration FileAccess.Write

Create

Delete the file, and then create a new file

Create a new file

CreateNew

Throw exception

Create a new file

Open

Open an existing file, and the stream points to the beginning of the file

Throw exception

OpenOrCreate

Open file, stream point to the beginning of the file

Create a new file

Truncate

Open an existing file and clear its contents. Stream points to the beginning of the file, preserving the initial creation date of the file

Throw exception

The FileStream class operates on byte and byte arrays, while the Stream class operates on character data
StreamWriter allows characters and strings to be written to the file, which handles the underlying transformations and writes data to the FileStream object. StreamReader is similar.
Instance:
Using System;
Using System.Data;
Using System.IO;
Using System.Text;

Summary description for Filereadandwrite
public class Filereadandwrite
{
Public Filereadandwrite ()
{
Todo:add constructor Logic here
}
Write files with FileStream
public void Filestreamwritefile (String str)
{
Byte[] Bydata;
Char[] Chardata;
Try
{
FileStream nFile = new FileStream ("Love.txt", FileMode.Create);
Get an array of characters
Chardata = str. ToCharArray ();
Initializing a byte array
Bydata = new Byte[chardata.length];
Converts a character array to the correct byte format
Encoder enc = Encoding.UTF8.GetEncoder ();
Enc. GetBytes (chardata, 0, chardata.length,bydata,0,true);
Nfile.seek (0, Seekorigin.begin);
Nfile.write (bydata, 0, bydata.length);
}
catch (Exception ex)
{
Throw ex;
}
}
FileStream reading files
public string Filestreamreadfile (string filePath)
{
byte[] data = new BYTE[100];
char[] Chardata = new char[100];
Try
{
FileStream file = new FileStream (FilePath, FileMode.Open);
The file pointer points to a 0-bit
File. Seek (0, Seekorigin.begin);
Read in 200 bytes
File. Read (data, 0, 200);
Extracting a byte array
Decoder Dec = Encoding.UTF8.GetDecoder ();
Dec. GetChars (data, 0, data. Length, Chardata, 0);
}
catch (Exception ex)
{
Throw ex;
}
Return convert.tostring (Chardata);
}
StreamWriter writing files
public void Streamwriterwritefile ()
{
Try
{
FileStream nFile = new FileStream ("Love.txt", filemode.createnew);
StreamWriter writer = new StreamWriter (nFile);

Writer. WriteLine ("I love you!");
Writer. WriteLine ("Do Your Love me!");
Writer. Close ();
}
Catch
{ }
}
StreamReader reading files
public string Streamreaderreadfile ()
{
String Str= "";
Try
{
FileStream file = new FileStream ("Love.txt", FileMode.Open);
StreamReader sr = new StreamReader (file);
while (Sr. ReadLine ()!=null)
{
str + = Sr. ReadLine ();
}
or str = Sr. ReadToEnd ();
Sr. Close ();
}
Catch
{ }
return str;
}
}

The difference between FileStream and Streamwriter/streamreader in C #

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.