实例介绍
【实例简介】
【实例截图】
【核心代码】
using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; namespace FTP24CP { public partial class Form1 : Form { string ftpServerIP; string ftpUserID; string ftpPassword; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { ftpServerIP = "192.168.1.21"; ftpUserID = "administrator"; ftpPassword = "xxxxx"; txtServerIP.Text = ftpServerIP; txtUsername.Text = ftpUserID; txtPassword.Text = ftpPassword; this.Text = ftpServerIP; btnFTPSave.Enabled = false; } /// <summary> /// Method to upload the specified file to the specified FTP Server /// </summary> /// <param name="filename">file full name to be uploaded</param> private void Upload(string filename) { FileInfo fileInf = new FileInfo(filename); string uri = "ftp://" ftpServerIP "/" fileInf.Name; FtpWebRequest reqFTP; // Create FtpWebRequest object from the Uri provided reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" ftpServerIP "/" fileInf.Name)); // Provide the WebPermission Credintials reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); // By default KeepAlive is true, where the control connection is not closed // after a command is executed. reqFTP.KeepAlive = false; // Specify the command to be executed. reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // Specify the data transfer type. reqFTP.UseBinary = true; // Notify the server about the size of the uploaded file reqFTP.ContentLength = fileInf.Length; // The buffer size is set to 2kb int buffLength = 2048; byte[] buff = new byte[buffLength]; int contentLen; // Opens a file stream (System.IO.FileStream) to read the file to be uploaded FileStream fs = fileInf.OpenRead(); try { // Stream to which the file to be upload is written Stream strm = reqFTP.GetRequestStream(); // Read from the file stream 2kb at a time contentLen = fs.Read(buff, 0, buffLength); // Till Stream content ends while (contentLen != 0) { // Write Content from the file stream to the FTP Upload Stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } // Close the file stream and the Request Stream strm.Close(); fs.Close(); } catch(Exception ex) { MessageBox.Show(ex.Message, "Upload Error"); } } public void DeleteFTP(string fileName) { try { string uri = "ftp://" ftpServerIP "/" fileName; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" ftpServerIP "/" fileName)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.DeleteFile; string result = String.Empty; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); long size = response.ContentLength; Stream datastream = response.GetResponseStream(); StreamReader sr = new StreamReader(datastream); result = sr.ReadToEnd(); sr.Close(); datastream.Close(); response.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message, "FTP 2.0 Delete"); } } private string[] GetFilesDetailList() { string[] downloadFiles; try { StringBuilder result = new StringBuilder(); FtpWebRequest ftp; ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" ftpServerIP "/")); ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword); ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails; WebResponse response = ftp.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string line = reader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = reader.ReadLine(); } result.Remove(result.ToString().LastIndexOf("\n"), 1); reader.Close(); response.Close(); return result.ToString().Split('\n'); //MessageBox.Show(result.ToString().Split('\n')); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); downloadFiles = null; return downloadFiles; } } public string[] GetFileList() { string[] downloadFiles; StringBuilder result = new StringBuilder(); FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" ftpServerIP "/")); reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.Method = WebRequestMethods.Ftp.ListDirectory; WebResponse response = reqFTP.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); //MessageBox.Show(reader.ReadToEnd()); string line = reader.ReadLine(); while (line != null) { result.Append(line); result.Append("\n"); line = reader.ReadLine(); } result.Remove(result.ToString().LastIndexOf('\n'), 1); reader.Close(); response.Close(); //MessageBox.Show(response.StatusDescription); return result.ToString().Split('\n'); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); downloadFiles = null; return downloadFiles; } } private void Download(string filePath, string fileName) { FtpWebRequest reqFTP; try { //filePath = <<The full path where the file is to be created.>>, //fileName = <<Name of the file to be created(Need not be the name of the file on FTP server).>> FileStream outputStream = new FileStream(filePath "\\" fileName, FileMode.Create); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" ftpServerIP "/" fileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); long cl = response.ContentLength; int bufferSize = 2048; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnUpload_Click(object sender, EventArgs e) { OpenFileDialog opFilDlg = new OpenFileDialog(); if (opFilDlg.ShowDialog() == DialogResult.OK) { Upload(opFilDlg.FileName); } } private void btnDownload_Click(object sender, EventArgs e) { FolderBrowserDialog fldDlg = new FolderBrowserDialog(); if (txtUpload.Text.Trim().Length > 0) { if (fldDlg.ShowDialog() == DialogResult.OK) { Download(fldDlg.SelectedPath, txtUpload.Text.Trim()); } } else { MessageBox.Show("Please enter the File name to download"); } } private void btnLstFiles_Click(object sender, EventArgs e) { string[] filenames = GetFileList(); lstFiles.Items.Clear(); foreach (string filename in filenames) { lstFiles.Items.Add(filename); } } private void btndelete_Click(object sender, EventArgs e) { OpenFileDialog fldDlg = new OpenFileDialog(); if (txtUpload.Text.Trim().Length > 0) { DeleteFTP(txtUpload.Text.Trim()); } else { MessageBox.Show("Please enter the File name to delete"); } } private long GetFileSize(string filename) { FtpWebRequest reqFTP; long fileSize = 0; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" ftpServerIP "/" filename)); reqFTP.Method = WebRequestMethods.Ftp.GetFileSize; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); fileSize = response.ContentLength; ftpStream.Close(); response.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } return fileSize; } private void Rename(string currentFilename, string newFilename) { FtpWebRequest reqFTP; try { reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" ftpServerIP "/" currentFilename)); reqFTP.Method = WebRequestMethods.Ftp.Rename; reqFTP.RenameTo = newFilename; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void MakeDir(string dirName) { FtpWebRequest reqFTP; try { // dirName = name of the directory to create. reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" ftpServerIP "/" dirName)); reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); ftpStream.Close(); response.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnFileSize_Click(object sender, EventArgs e) { long size = GetFileSize(txtUpload.Text.Trim()); MessageBox.Show(size.ToString() " bytes"); } private void button1_Click(object sender, EventArgs e) { Rename(txtCurrentFilename.Text.Trim(), txtNewFilename.Text.Trim()); } private void btnewDir_Click(object sender, EventArgs e) { MakeDir(txtNewDir.Text.Trim()); } private void txtPassword_TextChanged(object sender, EventArgs e) { btnFTPSave.Enabled = true; } private void txtServerIP_TextChanged(object sender, EventArgs e) { btnFTPSave.Enabled = true; } private void txtUsername_TextChanged(object sender, EventArgs e) { btnFTPSave.Enabled = true; } private void btnFTPSave_Click(object sender, EventArgs e) { ftpServerIP = txtServerIP.Text.Trim(); ftpUserID = txtUsername.Text.Trim(); ftpPassword = txtPassword.Text.Trim(); btnFTPSave.Enabled = false; } private void btnFileDetailList_Click(object sender, EventArgs e) { string[] filenames = GetFilesDetailList(); lstFiles.Items.Clear(); foreach (string filename in filenames) { lstFiles.Items.Add(filename); } } private void lstFiles_SelectedIndexChanged(object sender, EventArgs e) { } } }
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论