03.01.2015 Views

C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

Visual Studio 2013 C# 5.0 Programmer's Reference

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Getting FTP Information ❘ 457<br />

3. Set the object’s Credentials property.<br />

4. Call the request’s GetResponse method to get a WebResponse.<br />

5. Call the response’s GetResponseStream method to get the response stream.<br />

6. Process the stream.<br />

The FtpGetFileInfo example program, which is available for download on this book’s website, uses<br />

the following code to get the length of a file.<br />

// Use FTP to get a remote file's size.<br />

private long FtpGetFileSize(string url, string username, string password)<br />

{<br />

// Make a FtpRequest object.<br />

WebRequest request = WebRequest.Create(url);<br />

request.Method = WebRequestMethods.Ftp.GetFileSize;<br />

// Set network credentials.<br />

request.Credentials = new NetworkCredential(username, password);<br />

}<br />

using (WebResponse response = request.GetResponse())<br />

{<br />

// Return the size.<br />

return response.ContentLength;<br />

}<br />

This code simply follows the steps outlined earlier.<br />

The program uses the following code to get a file’s last modification time.<br />

// Use FTP to get a remote file's timestamp.<br />

private DateTime FtpGetFileTimestamp(string uri, string username, string password)<br />

{<br />

// Get the object used to communicate with the server.<br />

WebRequest request = WebRequest.Create(uri);<br />

request.Method = WebRequestMethods.Ftp.GetDateTimestamp;<br />

// Get network credentials.<br />

request.Credentials = new NetworkCredential(username, password);<br />

}<br />

// Return the last modification time.<br />

using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())<br />

{<br />

return response.LastModified;<br />

}<br />

This code also follows the previously described steps but with one twist. The LastModified property<br />

is defined in the FtpWebResponse class, not in the WebResponse parent class. That means the code<br />

must cast the generic WebResponse returned by the GetReponse method into its true identity: an<br />

FtpWebResponse object.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!