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 content of the user.config file looks like this:

ftp://127.0.0.1

anonymous1

password

Each user (of your computer) will maintain his own copy of the user.configfile.

Coding the Application

Now to code the application. Switching to the code-behind of Form1, import the following namespaces:

using System.Net;

using System.IO;

Define the WebRequestMethodenumeration:

namespace PhotoViewer {

enum WebRequestMethod {

MakeDirectory,

DownloadFile,

ListDirectoryDetails,

RemoveDirectory,

DeleteFile

}

Declare the following constants and member variables:

public partial class Form1 : Form {

//---constants for the icon images---

const int ico_OPEN = 0;

const int ico_CLOSE = 1;

const int ico_PHOTO = 2;

In Form1, select the three TextBoxcontrols (you can Ctrl+click each of them) that ask for the FTP server name, user name, and password (see Figure 16-9). In the Properties window, double-click the Leaveproperty to generate an event handler stub for the Leaveevent.

Figure 169 Visual Studio 2008 then generates the txtFtpServerLeaveevent - фото 264

Figure 16-9

Visual Studio 2008 then generates the txtFtpServer_Leaveevent handler:

private void txtFTPServer_Leave(object sender, EventArgs e) {

}

The event handler is invoked whenever the focus leaves one of the three TextBoxcontrols you have selected. This is where you can save the information entered by the user into the application settings you have created in the previous section.

Code the event handler as follows:

private void txtFTPServer_Leave(object sender, EventArgs e) {

//---save the values in the textbox controls

// into the application settings---

Properties.Settings.Default.FTP_SERVER = txtFTPServer.Text;

Properties.Settings.Default.UserName = txtUserName.Text;

Properties.Settings.Default.Password = txtPassword.Text;

Properties.Settings.Default.Save();

}

You access the various application settings using the Properties.Settings.Defaultclass (as generated in the Settings.Designer.csfile). Once the application settings are assigned a value, you need to persist them using the Save()method.

Building the Directory Tree and Displaying Images

When the form is loaded, you first load the values of the application settings into the TextBoxcontrols, and then display a node representing the root directory of the FTP server in the TreeViewcontrol:

private void Form1_Load(object sender, EventArgs e) {

try {

//---load the application settings values

// into the textbox controls---

txtFTPServer.Text = Properties.Settings.Default.FTP_SERVER;

txtUserName.Text = Properties.Settings.Default.UserName;

txtPassword.Text = Properties.Settings.Default.Password;

//---create the root node for the TreeView---

TreeNode node = new TreeNode();

node.ImageIndex = ico_CLOSE;

node.SelectedImageIndex = ico_OPEN;

node.Text = @"/";

//---add the root node to the control---

TreeView1.Nodes.Add(node);

//---add the dummy child node to the root node---

node.Nodes.Add("");

//---select the root node---

TreeView1.SelectedNode = node;

} catch (Exception ex) {

MessageBox.Show(ex.ToString());

}

}

You will always add a dummy node in the TreeViewcontrol after a node is created to ensure that the current node can be expanded to reveal subdirectories (even if there are none). This is shown in Figure 16-10.

C 2008 Programmers Reference - изображение 265

Figure 16-10

When a node is expanded (by clicking on the +symbol), the TreeView1_BeforeExpandevent is fired. You have to write code that checks to see if the current node is a leaf node (meaning that it is not a directory but a file). If it is a leaf node, exit the method. Otherwise, you need to display its subdirectories (if any).

You should also change the current node icon to "open" if the node is selected and "closed" if the node is not selected. Here's the code for expanding folders and displaying the proper icon at each node:

private void TreeView1_BeforeExpand(

object sender, TreeViewCancelEventArgs e) {

//---if leaf node (photo) then exit---

if (e.Node.ImageIndex == ico_PHOTO) return;

//---remove the dummy node and display the subdirectories and files---

try {

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

e.Node.Nodes.Clear();

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

BuildDirectory(e.Node);

} catch (Exception ex) {

ToolStripStatusLabel1.Text = ex.ToString();

}

//---change the icon for this node to open---

if (e.Node.GetNodeCount(false) > 0) {

e.Node.ImageIndex = ico_CLOSE;

e.Node.SelectedImageIndex = ico_OPEN;

}

}

The BuildDirectory()function displays all the files and subdirectories within the current directory in the TreeViewcontrol. Before you look at the definition of the BuildDirectory()function, you define the GetDirectoryListing()function, whose main job is to request from the FTP server the directory listing of a specified path:

//---Get the file/dir listings and return them as a string array---

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

Интервал:

Закладка:

Сделать

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

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


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

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

x