C # FileStream objects

Source: Internet
Author: User

The FileStream object represents a stream that points to a file on a disk or network path. These functions are often performed using StreamReader or StreamWriter when the class provides methods to read and write bytes to a file. This is because the FileStream class operates on byte and byte arrays, while the Stream class operates on character data. Character data is easy to use, but some operations, such as random file access, must be performed by the FileStream object.

FileStream constructor for the object:

FileStream afile = new FileStream ("Log.txt", FileMode.OpenOrCreate);

The FileMode enumeration has several members:

Append------If the file exists, open the file, move the file location to the end of the file, and create a new file. Filemode.append can only be used in conjunction with enumeration FileAccess.Write

The create------creates a new file, and if such a file exists, destroys it.

CreateNew creates a new file------, but throws an exception if the file already exists

Open------Opens an existing file, but does not have the specified file, throws an exception

OpenOrCreate------If the file exists, it is required to open the file, otherwise a new file is created, and the data remains in the file if the file already exists

Truncate------Open an existing file, clear its contents, and then we can write new data to the file, but keep the original creation date of the file, there must be a file, or throw an exception

Access level

The preceding constructor opens the file in read-only mode by default, requiring an additional parameter to specify a different access level, which is the FileAccess parameter.

FileStream afile=new FileStream ("Log.txt", Filemode.openorcreate,fileaccess.write)

There are three types of FileAccess enumerations: Read, Write, ReadWrite. This property does this by changing the user's access to the file based on the user's level of authentication

Read file location with Seek:public long Seek (long offset,seekorigin origin)

Long offset is the distance at which the file pointer moves in bytes; SeekOrigin origin is the starting position for the specified start calculation, which contains 3 values: Begin,current and end.

Example: Afile.seek (8,seekorigin.begin);//Seekorigin.begin refers to the file pointer from the first byte of the file, while the parameter ' 8 ' refers to moving to the 8th byte of a file

Example 2:afile. Seek (2,seekorigin.current)//start at the current position, then move 2 bytes.

Example 3:afile.seek ( -5,seekorigin.end)//start at the end of the file and count down to 5 bytes.

Reading data

Reading data using the FileStream class is not as easy as reading the data using the StreamReader and StreamWriter classes, because the FileStream class can only handle raw bytes (raw byey), This allows the FileStream class to be used in any data file, not just a text file, to read a file of similar images and sounds by reading byte data. The cost of this flexibility is that it cannot be read directly into the string, but can be handled using the StreamWriter and Streameader classes, since there are several conversion classes that can easily convert byte arrays to character arrays, or vice versa.

The Read () method is the primary means of accessing data from the file that the FileStream object points to:

public int Read (byte[] array,int offset, int count)//The first parameter is a byte array that is passed in to accept data from the FileStream object. The second parameter is the position in the byte array where the data is to be written, usually 0, representing the data to be written to the array from the beginning of the array, and the last parameter is how many bytes to read from the file.

Write Data

The process of writing the data is to get the byte array, then convert the byte data into a character array, and then write the character array to the file using the Write () method, while in the process of writing, you can determine where the file is written, how many characters are written, and so on.

Examples of file reads and writes:

Read file
Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.IO;

Namespace MyFile
{
Class Program
{
static void Main (string[] args)
{
byte[] Bydata = new byte[100];//set up a byte group to use for FileStream
char[] Chardata = new char[100];//set up a character group

Try
{
FileStream afile = new FileStream (".. /.. /.. /.. /data.txt ", filemode.open);//Instantiate a FileStream object to manipulate the Data.txt file, the type of operation is

Afile.seek (Seekorigin.begin);//Pointer to the file, the byte from the beginning of the file to the forward 55-byte point
Afile.read (bydata, 0, 100);//reads the file referred to by the FileStream object into a byte array
}
catch (IOException E)
{
Console.WriteLine ("Close");
Return
}
Decoder d = Encoding.UTF8.GetDecoder ();//
D.getchars (bydata, 0, Bydata.length, chardata, 0);//convert encoded byte arrays to character arrays

Console.WriteLine (Chardata);
Console.ReadLine ();
Return
}
}
}

Write file:

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.IO;

Namespace MyFile
{
Class Program
{
static void Main (string[] args)
{
byte[] Bydata = new byte[100];//set up a byte group to use for FileStream
char[] Chardata = new char[100];//set up a character group

Try
{
FileStream afile = new FileStream (".. /.. /.. /.. /data.txt ", filemode.open);//Instantiate a FileStream object to manipulate the Data.txt file, the type of operation is

Chardata = "Who am I?" 111? ". ToCharArray ();//copy characters within a string into a character group
Afile.seek (0, Seekorigin.end);
Encoder el = Encoding.UTF8.GetEncoder ();//Encoder
El. GetBytes (chardata, 0, Chardata.length, bydata, 0, true);

Afile.write (bydata, 0, bydata.length);
}
catch (IOException E)
{
Console.WriteLine ("Close");
Return
}

}
}
}

C # 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.