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

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

Интервал:

Закладка:

Сделать

private string[] GetDirectoryListing(string path) {

try {

//---get the directory listing---

FtpWebResponse FTPResp = PerformWebRequest(

path, WebRequestMethod.ListDirectoryDetails);

//---get the stream containing the directory listing---

Stream ftpRespStream = FTPResp.GetResponseStream();

StreamReader reader =

new StreamReader(ftpRespStream, System.Text.Encoding.UTF8);

//---obtain the result as a string array---

string[] result = reader.ReadToEnd().Split(

Environment.NewLine.ToCharArray(),

StringSplitOptions.RemoveEmptyEntries);

FTPResp.Close();

return result;

} catch (Exception ex) {

MessageBox.Show(ex.ToString());

return null;

}

}

To view the directory listing of an FTP server, you make use of the PerformWebRequest()helper function, which is defined as follows:

private FtpWebResponse PerformWebRequest(

string path, WebRequestMethod method) {

//---display the hour glass cursor---

Cursor.Current = Cursors.WaitCursor;

FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(path);

switch (method) {

case WebRequestMethod.DeleteFile:

ftpReq.Method = WebRequestMethods.Ftp.DeleteFile;

break;

case WebRequestMethod.DownloadFile:

ftpReq.Method = WebRequestMethods.Ftp.DownloadFile;

break;

case WebRequestMethod.ListDirectoryDetails:

ftpReq.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

break;

case WebRequestMethod.MakeDirectory:

ftpReq.Method = WebRequestMethods.Ftp.MakeDirectory;

break;

case WebRequestMethod.RemoveDirectory:

ftpReq.Method = WebRequestMethods.Ftp.RemoveDirectory;

break;

}

ftpReq.Credentials = new NetworkCredential(

Properties.Settings.Default.UserName,

Properties.Settings.Default.Password);

FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();

//---change back the cursor---

Cursor.Current = Cursors.Default;

return ftpResp;

}

The PerformWebRequest()function contains two parameters:

□ A path representing the full FTP path

□ A WebRequestMethodenumeration representing the type of request you are performing

In the PerformWebRequest()function, you perform the following:

□ Create an instance of the FtpWebRequestclass, using the WebRequestclass's Create()method. Create()takes in a URI parameter (containing the full FTP path).

□ Set the command to be sent to the FTP server, using the Methodproperty of the FtpWebRequestobject.

□ Specify the login credential to the FTP server, using the NetWorkCredentialclass.

□ Obtain the response from the FTP server, using the GetResponse()method from the FtpWebRequestclass.

The PerformWebRequest()function returns a FtpWebResponseobject.

Back in the GetDirectoryListing()function, after the call to PerformWebRequest()returns, you retrieve the stream containing the response data sent by the FTP server, using the GetResponseStream()method from the FtpWebResponseclass. You then use a StreamReaderobject to read the directory listing:

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

private string[] GetDirectoryListing(string path) {

try {

//---get the directory listing---

FtpWebResponse FTPResp = PerformWebRequest(

path, WebRequestMethod.ListDirectoryDetails);

//---get the stream containing the directory listing---

Stream ftpRespStream = FTPResp.GetResponseStream();

StreamReader reader =

new StreamReader(ftpRespStream, System.Text.Encoding.UTF8);

//---obtain the result as a string array---

string[] result = reader.ReadToEnd().Split(

Environment.NewLine.ToCharArray(),

StringSplitOptions.RemoveEmptyEntries);

FTPResp.Close();

return result;

} catch (Exception ex) {

MessageBox.Show(ex.ToString());

return null;

}

}

The directory listing is split into a string array. The directory listings are separated by newline characters. If your FTP server is configured with an MS-DOS directory listing style (see Figure 16-11), the directory listing will look something like this:

12-11-06 10:54PM 2074750 DSC00098.JPG

12-11-06 10:54PM 2109227 DSC00099.JPG

12-11-06 10:49PM

    George

    12-11-06 10:49PM

      James

      12-11-06 10:58PM

        Wei-Meng LeeFigure 1611 Because all subdirectories have the field you can easily - фото 266

        Figure 16-11

        Because all subdirectories have the

          field, you can easily differentiate subdirectories from files in the BuildDirectory()function by looking for
            in each line:

            //---Build the directory in the TreeView control---

            private void BuildDirectory(TreeNode ParentNode) {

            string[] listing = GetDirectoryListing(

            Properties.Settings.Default.FTP_SERVER + ParentNode.FullPath);

            foreach (string line in listing) {

            if (line == String.Empty) break;

            TreeNode node = new TreeNode();

            if (line.Substring(24, 5) == "

              ") {

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

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

Интервал:

Закладка:

Сделать

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

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


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

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

x