Книга: C# 2008 Programmer
Uploading Photos
Uploading Photos
To upload photos to the FTP server, you first select a folder to upload the photos to and then use the OpenFileDialog
class to ask the user to select the photo(s) he wants to upload. Finally, you upload the photos individually, using the UploadImage()
function:
private void btnUploadPhotos_Click(object sender, EventArgs e) {
//---ensure user selects a folder---
if (TreeView1.SelectedNode.ImageIndex == ico_PHOTO) {
MessageBox.Show("Please select a folder to upload the photos.");
return;
}
OpenFileDialog openFileDialog1 = new OpenFileDialog() {
Filter = "jpg files (*.jpg)|*.jpg",
FilterIndex = 2,
RestoreDirectory = true,
Multiselect = true
};
//---formulate the full path for the folder to be created---
string currentSelectedPath =
Properties.Settings.Default.FTP_SERVER +
TreeView1.SelectedNode.FullPath.Substring(1).Replace("r", "");
//---let user select the photos to upload---
if (openFileDialog1.ShowDialog() ==
System.Windows.Forms.DialogResult.OK) {
//---upload each photo individually---
for (int i = 0; i <= openFileDialog1.FileNames.Length - 1; i++) {
UploadImage(currentSelectedPath + "/" +
openFileDialog1.FileNames[i].Substring(
openFileDialog1.FileNames[i].LastIndexOf(@"") + 1),
openFileDialog1.FileNames[i]);
}
}
//---refresh the folder to show the uploaded photos---
RefreshCurrentFolder();
}
The UploadImage()
function uploads a photo from the hard disk to the FTP server:
? First, create a new instance of the WebClient
class.
? Specify the login credential to the FTP server.
? Upload the file to the FTP server, using the UploadFile()
method from the WebClient
class. Note that the full pathname of the file to be uploaded to the FTP server must be specified.
//---upload a photo to the FTP server---
private void UploadImage(string path, string filename) {
try {
WebClient client = new WebClient();
client.Credentials = new NetworkCredential(
Properties.Settings.Default.UserName,
Properties.Settings.Default.Password);
//---upload the photo---
client.UploadFile(path, filename);
//---update the statusbar---
ToolStripStatusLabel1.Text = filename + " uploaded!";
} catch (Exception ex) {
Console.WriteLine(ex.ToString());
}
}