Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

The BufferedStreamclass is ideal when you are manipulating large streams. The following shows how the previous example can be speeded up using the BufferedStreamclass:

try {

const int BUFFER_SIZE = 8192;

byte[] buffer = new byte[BUFFER_SIZE];

int bytesRead;

string filePath = @"C:\temp\VS2008Pro.png";

string filePath_backup = @"C:\temp\VS2008Pro_bak.png";

Stream s_in = File.OpenRead(filePath);

Stream s_out = File.OpenWrite(filePath_backup);

BufferedStream bs_in = new BufferedStream(s_in);

BufferedStream bs_out = new BufferedStream(s_out);

while ((bytesRead = bs_in.Read(buffer, 0, BUFFER_SIZE)) > 0) {

bs_out.Write(buffer, 0, bytesRead);

}

bs_out.Flush();

bs_in.Close();

bs_out.Close();

} catch (Exception ex) {

Console.WriteLine(ex.ToString());

}

You use a BufferedStreamobject over a Streamobject, and all the reading and writing is then done via the BufferedStreamobjects.

The FileStream Class

The FileStreamclass is designed to work with files, and it supports both synchronous and asynchronous read and write operations. Earlier, you saw the use of the Streamobject to read and write to file. Here is the same example using the FileStreamclass:

try {

const int BUFFER_SIZE = 8192;

byte[] buffer = new byte[BUFFER_SIZE];

int bytesRead;

string filePath = @"C:\temp\VS2008Pro.png";

string filePath_backup = @"C:\temp\VS2008Pro_bak.png";

FileStream fs_in = File.OpenRead(filePath);

FileStream fs_out = File.OpenWrite(filePath_backup);

while ((bytesRead = fs_in.Read(buffer, 0, BUFFER_SIZE)) > 0) {

fs_out.Write(buffer, 0, bytesRead);

}

fs_in.Dispose();

fs_out.Dispose();

fs_in.Close();

fs_out.Close();

} catch (Exception ex) {

Console.WriteLine(ex.ToString());

}

If the size of the file is large, this program will take a long time because it uses the blocking Read()method. A better approach would be to use the asynchronous read methods BeginRead()and EndRead().

BeginRead()starts an asynchronous read from a FileStreamobject. Every BeginRead()method called must be paired with the EndRead()method, which waits for the pending asynchronous read operation to complete. To read from the stream synchronously, you call the BeginRead()method as usual by providing it with the buffer to read, the offset to begin reading, size of buffer, and a call back delegate to invoke when the read operation is completed. You can also provide a custom object to distinguish different asynchronous operations (for simplicity you just pass in nullhere):

IAsyncResult result =

fs_in.BeginRead(buffer, 0, BUFFER_SIZE, new AsyncCallback(readCompleted), null);

The following program shows how you can copy the content of a file into another asynchronously:

class Program {

static FileStream fs_in;

static FileStream fs_out;

const int BUFFER_SIZE = 8192;

static byte[] buffer = new byte[BUFFER_SIZE];

static void Main(string[] args) {

try {

string filePath = @"C:\temp\VS2008Pro.png";

string filePath_backup = @"C:\temp\VS2008Pro_bak.png";

//---open the files for reading and writing---

fs_in = File.OpenRead(filePath);

fs_out = File.OpenWrite(filePath_backup);

Console.WriteLine("Copying file...");

//---begin to read asynchronously---

IAsyncResult result =

fs_in.BeginRead(buffer, 0, BUFFER_SIZE,

new AsyncCallback(readCompleted), null);

//---continue with the execution---

for (int i = 0; i < 100; i++) {

Console.WriteLine("Continuing with the execution...{0}", i);

System.Threading.Thread.Sleep(250);

}

} catch (Exception ex) {

Console.WriteLine(ex.ToString());

}

Console.ReadLine();

}

//---when a block of data is read---

static void readCompleted(IAsyncResult result) {

//---simulate slow reading---

System.Threading.Thread.Sleep(500);

//---reads the data---

int bytesRead = fs_in.EndRead(result);

//---writes to another file---

fs_out.Write(buffer, 0, bytesRead);

if (bytesRead > 0) {

//---continue reading---

result =

fs_in.BeginRead(buffer, 0, BUFFER_SIZE,

new AsyncCallback(readCompleted), null);

} else {

//---reading is done!---

fs_in.Dispose();

fs_out.Dispose();

fs_in.Close();

fs_out.Close();

Console.WriteLine("File copy done!");

}

}

}

Because the reading may happen so fast for a small file, you can insert Sleep()statements to simulate reading a large file. Figure 11-3 shows the output.

Figure 113 MemoryStream Sometimes you need to manipulate data in memory - фото 166

Figure 11-3

MemoryStream

Sometimes you need to manipulate data in memory without resorting to saving it in a file. A good example is the PictureBoxcontrol in a Windows Form. For instance, you have a picture displayed in the PictureBoxcontrol and want to send the picture to a remote server, say a Web Service. The PictureBoxcontrol has a Save()method that enables you to save the image to a Streamobject.

Instead of saving the image to a FileStreamobject and then reloading the data from the file into a byte array, a much better way would be to use a MemoryStreamobject, which uses the memory as a backing store (which is more efficient compared to performing file I/O; file I/O is relatively slower).

The following code shows how the image in the PictureBoxcontrol is saved into a MemoryStreamobject:

//---create a MemoryStream object---

MemoryStream ms1 = new MemoryStream();

//---save the image into a MemoryStream object---

pictureBox1.Image.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);

To extract the image stored in the MemoryStreamobject and save it to a byte array, use the Read()method of the MemoryStreamobject:

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x