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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

node.Text = line.Substring(39);

node.ImageIndex = ico_CLOSE;

node.SelectedImageIndex = ico_OPEN;

//---add the dummy child node---

node.Nodes.Add("");

ParentNode.Nodes.Add(node);

} else {

//---this is a normal file; create a new node to be added---

node.Text = line.Substring(39);

node.ImageIndex = ico_PHOTO;

node.SelectedImageIndex = ico_PHOTO;

ParentNode.Nodes.Add(node);

}

}

}

When a node is selected, you first obtain its current path and then display that path in the status bar if it is a folder. If it is an image node, download and display the photo, using the DownloadImage()function. All these are handled in the TreeView1_AfterSelectevent. Here's the code:

private void TreeView1_AfterSelect(object sender, TreeViewEventArgs e) {

//---always ignore the first "/" char---

string FullPath =

Properties.Settings.Default.FTP_SERVER +

e.Node.FullPath.Substring(1).Replace("\r", "");

//---display the current folder selected---

if (e.Node.ImageIndex != ico_PHOTO) {

ToolStripStatusLabel1.Text = FullPath;

return;

}

//---download image---

DownloadImage(FullPath);

}

The DownloadImage()function downloads an image from the FTP server and displays the image in a PictureBox control:

//---Download the image from the FTP server---

private void DownloadImage(string path) {

try {

ToolStripStatusLabel1.Text = "Downloading image..." + path;

Application.DoEvents();

//---download the image---

FtpWebResponse FTPResp =

PerformWebRequest(path, WebRequestMethod.DownloadFile);

//---get the stream containing the image---

Stream ftpRespStream = FTPResp.GetResponseStream();

//---display the image---

PictureBox1.Image = Image.FromStream(ftpRespStream);

FTPResp.Close();

ToolStripStatusLabel1.Text =

"Downloading image...complete(" + path + ")";

} catch (Exception ex) {

MessageBox.Show(ex.Message);

}

}

To download an image file using FTP and then bind it to a PictureBoxcontrol:

□ Call the PerformWebRequest()helper function you defined earlier.

□ Retrieve the stream that contains response data sent from the FTP server, using the GetResponseStream()method from the FtpWebResponseclass.

To set the PictureBoxcontrol to display the downloaded image, use the FromStream()method from the Image class to convert the response from the FTP server (containing the image) into an image.

Creating a New Directory

The user can create a new directory on the FTP server by clicking the Create Folder button. To create a new directory, select a node (by clicking on it) to add the new folder, and then call the PerformWebRequest()helper function you defined earlier. This is accomplished by the Create Folder button:

//---Create a new folder---

private void btnCreateFolder_Click(object sender, EventArgs e) {

//---ensure user selects a folder---

if (TreeView1.SelectedNode.ImageIndex == ico_PHOTO) {

MessageBox.Show("Please select a folder first.");

return;

}

try {

//---formulate the full path for the folder to be created---

string folder = Properties.Settings.Default.FTP_SERVER +

TreeView1.SelectedNode.FullPath.Substring(1).Replace("\r", "") +

@"/" + txtNewFolderName.Text;

//---make the new directory---

FtpWebResponse ftpResp =

PerformWebRequest(folder, WebRequestMethod.MakeDirectory);

ftpResp.Close();

//---refresh the newly added folder---

RefreshCurrentFolder();

//---update the statusbar---

ToolStripStatusLabel1.Text =

ftpResp.StatusDescription.Replace("\r\n",string.Empty);

} catch (Exception ex) {

MessageBox.Show(ex.ToString());

}

}

When a new folder is created, you update the TreeView control to reflect the newly added folder. This is accomplished by the RefreshCurrentFolder()function:

private void RefreshCurrentFolder() {

//---clears all the nodes and...---

TreeView1.SelectedNode.Nodes.Clear();

//---...create the nodes again---

BuildDirectory(TreeView1.SelectedNode);

}

Removing a Directory

To remove (delete) a directory, a user first selects the folder to delete and then clicks the Remove Folder button. To delete a directory, you call the PerformWebRequest()helper function you defined earlier. This is accomplished with the Remove Folder button:

//---Remove a folder---

private void btnRemoveFolder_Click(object sender, EventArgs e) {

if (TreeView1.SelectedNode.ImageIndex == ico_PHOTO) {

MessageBox.Show("Please select a folder to delete.");

return;

}

try {

string FullPath =

Properties.Settings.Default.FTP_SERVER +

TreeView1.SelectedNode.FullPath.Substring(1).Replace("\r", "");

//---remove the folder---

FtpWebResponse ftpResp =

PerformWebRequest(FullPath, WebRequestMethod.RemoveDirectory);

//---delete current node---

TreeView1.SelectedNode.Remove();

//---update the statusbar---

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

Интервал:

Закладка:

Сделать

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

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


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

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

x