Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Лаба №1 / books / csharp_ebook.pdf
Скачиваний:
89
Добавлен:
03.03.2016
Размер:
4 Мб
Скачать
☆

Programmers Heaven: C# School

A FileAccess enumeration instance defines which operations are allowed during the file access. The possible values include Read, Write and ReadWrite. If FileAccess is Read, you can only read from the file stream.

A FileShare enumeration instance that defines the sharing options for the file. The possible values include None, Read, ReadWrite, Write. If FileShare is None, no other stream can open this file until you have got this stream open. If FileShare is Read, other streams can open and only read from this file.

Opening and reading from a file

Now we've got a good grasp of the theory of file streams, let's do something practical. In practice, handling a file stream is as easy as anything else in C#. Let’s create a windows application that reads a file into a text box, allows the user to change the text and saves it back to the file. The application will finally look like:

The code behind it is very simple. The event handler for the Read File button (btnGo) is:

private void btnGo_Click(object sender, System.EventArgs e)

{

string fileName = "C:\\C-sharp.txt";

lblFileName.Text = "File Name: " + fileName;

304

Programmers Heaven: C# School

// Open existing file in Read only mode without allowing any sharing

FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);

//create an array of bytes of the size of file\

//and read file contents to it.

byte[] byteText = new byte[fs.Length]; fs.Read(byteText, 0, byteText.Length);

//convert bytes array to string and display in the text box txtFileText.Text = System.Text.Encoding.ASCII.GetString(byteText);

//close the file stream so that other streams may use it fs.Close();

}

Here, we have used the file stream to open the existing file (FileMode.Open) in read only mode (FileAccess.Read) and without allowing any other stream to use it while our application is using this file (FileShare.None). We then created an array of bytes with length equal to the length of the file and read the file into it.

fs.Read(byteText, 0, byteText.Length);

Here we have specified that we want to read the file contents into the byteText array, that the file stream should start filling the array from the ‘0’ index and that it should read byteText.Length (size of file) bytes from the file. After reading the contents, we need to convert the byte array to a string so that it can be displayed in the text box. Finally, we have closed the stream (and thus the file) so that other streams may access it.

Similarly, the event handler for Save File button (btnSaveFile) is:

private void btnSaveFile_Click(object sender, System.EventArgs e)

{

string fileName = "C:\\C-sharp.txt";

// Open existing file in Read only mode without allowing any sharing

FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Write, FileShare.None);

//covert the text (string) in the text box to bytes array

//and make the byteText reference to point to that byte array

byte[] byteText = System.Text.Encoding.ASCII.GetBytes(txtFileText.Text);

// write the byte array to file from the start to end fs.Write(byteText, 0, byteText.Length);

305

Programmers Heaven: C# School

// close the file stream so that other streams may use it

fs.Close();

}

Here we have first converted the text in the text box to a byte array and then written it to the file using FileStream class’ Write() method:

fs.Write(byteText, 0, byteText.Length);

In the above line we have told the FileStream class to write the bytes in the byteText array to the associated file. We have asked it to start writing from the first byte of the array and write the complete array to the file.

Using BinaryReader and BinaryWriter to read and write primitives to files

The problem with using the FileStream class is that we can only read and write bytes to the file. We have to explicitly convert other types of data (int, double, bool, string) to bytes before writing to the file (and vice versa for reading). The Dot Net (.Net) framework class library provides two classes that allow us to read and write primitive data types to a file. We can use System.IO.BinaryReader to read primitive data types from a file and System.IO.BinaryWriter to write primitives to the file.

An important point about the BinaryReader and BinaryWriter classes is that they need a stream to be passed in their constructor. These classes use the stream to read and write primitives.

Let’s create an application that writes different primitives to a file and then read them back. The application will finally look like this:

306

Programmers Heaven: C# School

The text box in the application is read only. At first, the Read File button is also disabled and the user needs to select the Save File button to save the file first, and then read the file back to the text box. The contents written to the file are hard coded in the Save File button’s click event handler which is:

private void btnSaveFile_Click(object sender, System.EventArgs e)

{

string fileName = "C:\\C-sharp.txt";

// Open existing file in Read only mode without allowing any sharing

FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Write, FileShare.None);

//Open the Writer over this file stream BinaryWriter writer = new BinaryWriter(fs);

//write different types of primitives to the file writer.Write("I am Fraz\r\n");

writer.Write("Age: "); writer.Write(23); writer.Write("\r\nWeight: "); writer.Write(45.5);

//close the file stream so that other streams may use it writer.Close();

fs.Close();

btnLoadFile.Enabled = true;

}

Here we have first created the file stream and used it to instantiate the BinaryWriter class. We have then written different primitives to the stream using BinaryWriter’s Write() method, which has many overloaded versions to write different type of primitives. Finally we have closed the two streams and enabled the Load File button.

The event handler for the Load File button is:

private void btnGo_Click(object sender, System.EventArgs e)

{

string fileName = "C:\\C-sharp.txt"; lblFileName.Text = "File Name: " + fileName;

// Open existing file in Read only mode without allowing any sharing

FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);

307

Соседние файлы в папке books