net上傳ftp
⑴ asp.net中上傳文件到遠程ftp伺服器指定目錄下,求大神幫助,小弟不勝感激
private string ftpServerIP = "伺服器ip";//伺服器ip
private string ftpUserID = "ftp的用戶名";//用戶名
private string ftpPassword = "ftp的密碼";//密碼
//filename 為本地文件的絕對路徑
//serverDir為伺服器上的目錄
private void Upload(string filename,string serverDir)
{
FileInfo fileInf = new FileInfo(filename);
string uri = string.Format("ftp://{0}/{1}/{2}", ftpServerIP,serverDir,fileInf.Name);
FtpWebRequest reqFTP;
// 根據uri創建FtpWebRequest對象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
// ftp用戶名和密碼
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
// 默認為true,連接不會被關閉
// 在一個命令之後被執行
reqFTP.KeepAlive = false;
// 指定執行什麼命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// 指定數據傳輸類型
reqFTP.UseBinary = true;
// 上傳文件時通知伺服器文件的大小
reqFTP.ContentLength = fileInf.Length;
// 緩沖大小設置為2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// 打開一個文件流 (System.IO.FileStream) 去讀上傳的文件
FileStream fs = fileInf.OpenRead();
try
{
// 把上傳的文件寫入流
Stream strm = reqFTP.GetRequestStream();
// 每次讀文件流的2kb
contentLen = fs.Read(buff, 0, buffLength);
// 流內容沒有結束
while (contentLen != 0)
{
// 把內容從file stream 寫入 upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// 關閉兩個流
strm.Close();
fs.Close();
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message, "Upload Error");
Response.Write("Upload Error:" + ex.Message);
}
}
調用方法
string filename = "D:\\test.txt"; //本地文件,需要上傳的文件
string serverDir = "img"; //上傳到伺服器的目錄,必須存在
Upload(filename,serverDir);
⑵ vb.net ftp上傳文件
Dim OpenFileDialog As New OpenFileDialog
OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
OpenFileDialog.Filter = "文本文件(*.jpg)|*.jpg|所有文件(*.*)|*.*"
If (OpenFileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then
Dim FileName As String = OpenFileDialog.FileName
' TODO: 在此處添加打開文件的代碼。
textbox1.Text = FileName
End If
第一個按鈕 上傳
Dim filelast As String = fileaddbefore.Text.Substring(fileaddbefore.Text.LastIndexOf("."), fileaddbefore.Text.Length - fileaddbefore.Text.LastIndexOf("."))
MessageBox.Show(filelast)
My.Computer.Network.UploadFile(textbox1.Text, "ftp://XXX/" & 文件名.Text & filelast, "登錄名1", "登錄密碼", True, 100)
第二個按鈕