C#filestream file read/write (EXT) __c#

Source: Internet
Author: User

C # File stream write file, default append Filemode.append
String msg = "OKFFFFFFFFFFFFFFFF";
byte[] MyByte = System.Text.Encoding.UTF8.GetBytes (msg);
using (FileStream fswrite = new FileStream (@ "D:\1.txt", Filemode.append))
{
Fswrite.write (mybyte, 0, mybyte.length);
};
C # file stream read file
using (FileStream fsread = new FileStream (@ "D:\1.txt", FileMode.Open))
{
int fslen = (int) fsread.length;
byte[] Hebyte = new Byte[fslen];
int r = fsread.read (hebyte, 0, hebyte.length);
String mystr = System.Text.Encoding.UTF8.GetString (hebyte);
Console.WriteLine (MYSTR);
Console.readkey ();
}

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 performs these functions using StreamReader or StreamWriter. 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 (accessing data at a point in the middle of a file), must be performed by the FileStream object, which is described later.

There are several other ways to create a FileStream object. Constructors have many different overloaded versions, and the simplest constructors have only two parameters, namely file names and FileMode enumeration values.

FileStream afile = new FileStream (filename, filemode.member);

The FileMode enumeration has several members that specify how to open or create a file. These enumeration members are described later. Another common constructor is the following:

FileStream afile = new FileStream (filename, Filemode.member, FileAccess. Member);

The third parameter is a member of the FileAccess enumeration, which specifies the function of the stream. The members of the FileAccess enumeration are shown in table 22-6.

Table 22-6

Members

Description

Read

Open a file for read-only

Write

Open a file for writing only

ReadWrite

Open file for reading and writing

An operation specified on a file that is not a FileAccess enumeration member can cause an exception to be thrown. The purpose of this property is to change the user's access rights to the file based on the user's authentication level.

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

The FileMode enumeration member is shown in table 22-7. What happens with each value depends on whether the specified filename represents an existing file. Note that the entry in this table represents the location of the stream when the stream was created, and the topic is discussed in detail in the next section. Unless specifically stated, the stream points to the beginning of the file.

Table 22-7

Members

File exists

File does not exist

Append

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

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

Create

Delete the file, and then create a new file

Create a new file

CreateNew

Throw an exception

Create a new file

Open

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

Throw an exception

OpenOrCreate

Opens the file, and the stream points to the beginning of the file

Create a new file

Truncate

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

Throw an exception

Both the file and FileInfo classes provide the OpenRead () and Openwrite () methods, making it easier to create FileStream objects. The former opens a read-only access file, which only allows the file to be written. These provide shortcuts, so you do not have to provide all the preceding information in the form of arguments to the FileStream constructor. For example, the following line of code opens the Data.txt file for read-only access:

FileStream afile = File.openread ("Data.txt");

Note that the following code performs the same function:

FileInfo afileinfo = new FileInfo ("Data.txt");
FileStream afile = Afile.openread ();

1. File Location

The FileStream class maintains an internal file pointer that points to the location of the next read and write operation in the file. In most cases, when you open a file, it points to the beginning of the file, but this pointer can be modified. This allows the application to read and write anywhere in the file, randomly access the file, or jump directly to a specific location in the file. This is very time-saving when working with large files, because you can immediately navigate to the correct location.

The method for implementing this functionality is the Seek () method, which has two parameters: the first parameter sets the distance that the file pointer moves in bytes. The second parameter sets the starting position of the start calculation, represented by a value of the SeekOrigin enumeration. The Seek Origin enumeration contains 3 values: Begin, Current, and end.

For example, the following line of code moves the file pointer to the 8th byte of the file, starting at the 1th byte of the file:

Afile.seek (8,seekorigin.begin);

The following line of code moves the pointer forward 2 bytes, starting at the current position. If you execute the following code after the line above, the file pointer points to the 10th byte of the file:

Afile.seek (2,seekorigin.current);

Note that file pointers also change when you read and write files. After reading 10 bytes, the file pointer points to the byte after the 10th byte being read.

You can also specify a negative lookup location, which can be used in conjunction with the Seekorigin.end enumeration value to find a location close to the end of the file. The following code looks for the penultimate byte in the file:

Afile.seek (–5, seekorigin.end);

Files accessed in this manner are sometimes referred to as random access files because the application can access any location in the file. The stream class, which is described later, can continuously access the file and does not allow the file pointer to be manipulated in this manner.

2. Reading data

Reading data using the FileStream class is not as easy as reading data using the StreamReader class described later in this chapter. This is because the FileStream class can only handle raw bytes (raw byte). The ability to handle raw bytes enables the FileStream class to be used with any data file, not just a text file. By reading Byte data, the FileStream object can be used to read files for images and sounds. The price of this flexibility is that you cannot use the FileStream class to read data directly into a string, but you can do this with the StreamReader class. But there are several conversion classes that can easily convert a byte array to a character array, or do the opposite.

The FileStream.Read () method is the primary means of accessing data from a file that the FileStream object points to. This method reads the data from the file and writes the data to a byte array. It has three parameters: the first parameter is a byte array that is transferred in to accept the data in the FileStream object. The second parameter is where the data begins to be written in a byte array. It is usually 0, which means that the data is written to the file from the beginning of the array. The last parameter specifies how many bytes to read from the file.

The following example shows the reading of data from a random access file. The file to be read is actually the class file created for this example.

Try it: Read data from random access files

(1) Create a new console application ReadFile under the directory C:\BegVCSharp\Chapter22.

(2) Add the following using directive at the top of the Program.cs file:

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

(3) in the main () side

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.