C# ftp 上传、下载、删除

时间:2022-05-22 08:36:20
  public class FtpHelper
{
public static readonly FtpHelper Instance = new FtpHelper(); /// <summary>
/// 取得文件名
/// </summary>
/// <param name="ftpPath">ftp路径</param>
/// <returns></returns>
public string[] GetFilePath(string userId, string pwd, string ftpPath)
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(userId, pwd);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
reqFTP.UsePassive = false;
WebResponse response = reqFTP.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'), );
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
downloadFiles = null;
return downloadFiles;
}
} //ftp的上传功能
public void Upload(string userId, string pwd, string filename, string ftpPath)
{
FileInfo fileInf = new FileInfo(filename);
FtpWebRequest reqFTP;
// 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileInf.Name));
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(userId, pwd); reqFTP.UsePassive = false;
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// 指定数据传输类型
reqFTP.UseBinary = true;
// 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length;
// 缓冲大小设置为2kb
int buffLength = ;
byte[] buff = new byte[buffLength];
int contentLen;
// 打开一个文件流 (System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
try
{
// 把上传的文件写入流
Stream strm = reqFTP.GetRequestStream();
// 每次读文件流的2kb
contentLen = fs.Read(buff, , buffLength);
// 流内容没有结束
while (contentLen != )
{
// 把内容从file stream 写入 upload stream
strm.Write(buff, , contentLen);
contentLen = fs.Read(buff, , buffLength);
}
// 关闭两个流
strm.Close();
fs.Close();
}
catch (Exception ex)
{ }
} public void Delete(string userId, string pwd, string ftpPath, string fileName)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(userId, pwd);
reqFTP.UsePassive = false;
FtpWebResponse listResponse = (FtpWebResponse)reqFTP.GetResponse();
string sStatus = listResponse.StatusDescription;
}
catch (Exception ex)
{
throw ex;
}
} //从ftp服务器上下载文件的功能
public void Download(string userId, string pwd, string ftpPath, string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(userId, pwd);
reqFTP.UsePassive = false;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = ;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, , bufferSize);
while (readCount > )
{
outputStream.Write(buffer, , readCount);
readCount = ftpStream.Read(buffer, , bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close(); }
catch (Exception ex)
{
throw ex;
}
} }

http://blog.csdn.net/csethcrm/article/details/8139744

========================================

因公司要求,整理公司资源,把现有的资源上传的一个电脑上(在一个同事的电脑上腾出了空间,把所有的资源上传的此电脑上),我在这个电脑上装了SQL2008+serv_u+IIS7,我用的是c# winform+webservice,数据库操作通过webservice进行,上传文件用ftp批量上传,上传整个文件夹,一下是文件夹目录
C# ftp 上传、下载、删除
文件夹总大小100MB以上,有时候单独一个文件也有10-100mb左右,
一下是ftp上传代码

C# code
 

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public void Upload(string filename,string foldername)
        {
 
            try
            {
                FileInfo fileInf = new FileInfo(filename);
 
                string uri = "ftp://" + ftpServerIP + "/" + foldername + "/" + fileInf.Name;
 
                Connect(uri);//连接
 
                // 默认为true,连接不会被关闭
                // 在一个命令之后被执行
                reqFTP.KeepAlive = false;
 
                // 指定执行什么命令
 
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
 
                // 上传文件时通知服务器文件的大小
 
                reqFTP.ContentLength = fileInf.Length;
 
                // 缓冲大小设置为kb 
 
                int buffLength = 2048;
 
                byte[] buff = new byte[buffLength];
 
                int contentLen;
 
                // 打开一个文件流(System.IO.FileStream) 去读上传的文件
 
                FileStream fs = fileInf.OpenRead();
 
                try
                {
 
                    // 把上传的文件写入流
                    Stream strm = reqFTP.GetRequestStream();
 
                    // 每次读文件流的kb
                    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");
 
                }
            }
            catch
            { }
        }

可以通过遍历批量上传文件,但是上传速度很慢,很慢。上传一个文件夹都要花上半天,我想问有没有办法提高上传速度,或者要用别的上传方法。(用别的方法也可以,因为ftp上传我第一次接触,不太熟悉)请各位给个意见,小弟感激不尽!还有上传的时候要加上进度条。请各位大侠高手们帮忙。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
private void Form1_Load(object sender, EventArgs e)
        {
            ftpServerIP = "192.168.239.83";
            ftpUserID = "ftptest";
            ftpPassword = "test";
        }
 
        private void btnUpload_Click(object sender, EventArgs e)
        {
            OpenFileDialog opFilDlg = new OpenFileDialog();
            if (opFilDlg.ShowDialog() == DialogResult.OK)
            {
                Upload(opFilDlg.FileName);
            }
        }
 
      
 
        private void Upload(string filename)
        {
            FileInfo fileInf = new FileInfo(filename);
            string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
            FtpWebRequest reqFTP;
            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));
            reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            reqFTP.KeepAlive = false;
            reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
            reqFTP.UseBinary = true;
            reqFTP.ContentLength = fileInf.Length;
            int buffLength = 2048;
            byte[] buff = new byte[buffLength];
            int contentLen;
            FileStream fs = fileInf.OpenRead();
            try
            {
                Stream strm = reqFTP.GetRequestStream();
                contentLen = fs.Read(buff, 0, buffLength);
                while (contentLen != 0)
                {
                    strm.Write(buff, 0, contentLen);
                    contentLen = fs.Read(buff, 0, buffLength);
                }
                strm.Close();
                fs.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "上传出错");
                return;
            }
            MessageBox.Show("上传成功!");
        }

参考以上代码。

http://bbs.csdn.net/topics/391033851

=============================================================

net,C#,Ftp各种操作,上传,下载,删除文件,创建目录,删除目录,获得文件列表等

using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

using System.IO;

using System.Windows.Forms;

namespace ConvertData

{

class FtpUpDown

{

string ftpServerIP;

string ftpUserID;

string ftpPassword;

FtpWebRequest reqFTP;

private void Connect(String path)//连接ftp

{

// 根据uri创建FtpWebRequest对象

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));

// 指定数据传输类型

reqFTP.UseBinary = true;

// ftp用户名和密码

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

}

public FtpUpDown(string ftpServerIP, string ftpUserID, string ftpPassword)

{             this.ftpServerIP = ftpServerIP;

this.ftpUserID = ftpUserID;

this.ftpPassword = ftpPassword;         }

//都调用这个

private string[] GetFileList(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表

{             string[] downloadFiles;             StringBuilder result = new StringBuilder();             try

{                 Connect(path);

reqFTP.Method = WRMethods;

WebResponse response = reqFTP.GetResponse();

StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名

string line = reader.ReadLine();

while (line != null)

{

result.Append(line);

result.Append("\n");

line = reader.ReadLine();

}

// to remove the trailing '\n'

result.Remove(result.ToString().LastIndexOf('\n'), 1);

reader.Close();

response.Close();

return result.ToString().Split('\n');

}

catch (Exception ex)

{                 System.Windows.Forms.MessageBox.Show(ex.Message);

downloadFiles = null;

return downloadFiles;             }         }

public string[] GetFileList(string path)//上面的代码示例了如何从ftp服务器上获得文件列表

{             return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);         }         public string[] GetFileList()//上面的代码示例了如何从ftp服务器上获得文件列表

{             return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);         }

public void Upload(string filename) //上面的代码实现了从ftp服务器上载文件的功能

{             FileInfo fileInf = new FileInfo(filename);

string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

Connect(uri);//连接

// 默认为true,连接不会被关闭

// 在一个命令之后被执行

reqFTP.KeepAlive = false;

// 指定执行什么命令

reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

// 上传文件时通知服务器文件的大小

reqFTP.ContentLength = fileInf.Length;             // 缓冲大小设置为kb             int buffLength = 2048;             byte[] buff = new byte[buffLength];

int contentLen;

// 打开一个文件流(System.IO.FileStream) 去读上传的文件

FileStream fs = fileInf.OpenRead();

try

{

// 把上传的文件写入流

Stream strm = reqFTP.GetRequestStream();

// 每次读文件流的kb

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");

}

}

public bool Download(string filePath, string fileName, out string errorinfo)////上面的代码实现了从ftp服务器下载文件的功能

{             try

{                 String onlyFileName = Path.GetFileName(fileName);

string newFileName = filePath + "\\" + onlyFileName;

if (File.Exists(newFileName))

{

errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName);                     return false;                 }                 string url = "ftp://" + ftpServerIP + "/" + fileName;                 Connect(url);//连接                 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);

FileStream outputStream = new FileStream(newFileName, FileMode.Create);                 while (readCount > 0)

{                     outputStream.Write(buffer, 0, readCount);                     readCount = ftpStream.Read(buffer, 0, bufferSize);                 }                 ftpStream.Close();                 outputStream.Close();                 response.Close();

errorinfo = "";

return true;

}

catch (Exception ex)

{                 errorinfo = string.Format("因{0},无法下载", ex.Message);

return false;

}

}

//删除文件

public void DeleteFileName(string fileName)

{             try

{                 FileInfo fileInf = new FileInfo(fileName);

string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

Connect(uri);//连接

// 默认为true,连接不会被关闭

// 在一个命令之后被执行

reqFTP.KeepAlive = false;

// 指定执行什么命令

reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();                 response.Close();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message, "删除错误");

}

}

//创建目录

public void MakeDir(string dirName)

{             try

{                 string uri = "ftp://" + ftpServerIP + "/" + dirName;

Connect(uri);//连接

reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;

FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

response.Close();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

}

//删除目录

public void delDir(string dirName)

{             try

{                 string uri = "ftp://" + ftpServerIP + "/" + dirName;

Connect(uri);//连接

reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;

FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

response.Close();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

}

//获得文件大小

public long GetFileSize(string filename)

{

long fileSize = 0;

try

{

FileInfo fileInf = new FileInfo(filename);

string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

Connect(uri);//连接

reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;

FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

fileSize = response.ContentLength;

response.Close();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

return fileSize;

}

//文件改名

public void Rename(string currentFilename, string newFilename)

{             try

{                 FileInfo fileInf = new FileInfo(currentFilename);

string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;

Connect(uri);//连接

reqFTP.Method = WebRequestMethods.Ftp.Rename;

reqFTP.RenameTo = newFilename;

FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

//Stream ftpStream = response.GetResponseStream();

//ftpStream.Close();

response.Close();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

}

//获得文件明晰

public string[] GetFilesDetailList()

{

return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);

}

//获得文件明晰

public string[] GetFilesDetailList(string path)

{

return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectoryDetails);

}

} }

-----------------------

测试

//获得文件列表

private void button1_Click(object sender, EventArgs e)

{

FtpUpDown ftpUpDown = new FtpUpDown(ConvertData.Properties.Settings.Default.ftpServerIP, ConvertData.Properties.Settings.Default.ftpUserID, ConvertData.Properties.Settings.Default.ftpPassword);

string[] str = ftpUpDown.GetFileList("2005");

richTextBox1.Lines = str;

}

//下载

private void button2_Click(object sender, EventArgs e)

{

FtpUpDown ftpUpDown = new FtpUpDown(ConvertData.Properties.Settings.Default.ftpServerIP, ConvertData.Properties.Settings.Default.ftpUserID, ConvertData.Properties.Settings.Default.ftpPassword);

ftpUpDown.Download("c:\\", "2007/11/01/57070.pdf");

}

//上传

private void button3_Click(object sender, EventArgs e)

{

FtpUpDown ftpUpDown = new FtpUpDown(ConvertData.Properties.Settings.Default.ftpServerIP, ConvertData.Properties.Settings.Default.ftpUserID, ConvertData.Properties.Settings.Default.ftpPassword);

ftpUpDown.Upload("c:\\57070.pdf");

}

=================================================

C# ftp检测服务器是否存在目录,不存在就创建

using System.Net;
using System.Net.Sockets;

/// <summary>
        /// 检测目录是否存在
        /// </summary>
        /// <param name="ServerIP"></param>
        /// <param name="pFtpUserID"></param>
        /// <param name="pFtpPW"></param>
        /// <param name="FileSource"></param>

using System.Net;
using System.Net.Sockets;

/// <summary>
        /// 检测目录是否存在
        /// </summary>
        /// <param name="ServerIP"></param>
        /// <param name="pFtpUserID"></param>
        /// <param name="pFtpPW"></param>
        /// <param name="FileSource"></param>
        /// <param name="FileCategory"></param>
        /// <returns></returns>
        public static bool checkDirectory(string ServerIP, string pFtpUserID, string pFtpPW, string FileSource, string FileCategory)
        {
            //检测目录是否存在
            Uri uri = new Uri("ftp://" + ServerIP + "/" + FileSource + "/");
            if (!DirectoryIsExist(uri, pFtpUserID, pFtpPW))
            {
                //创建目录
                uri = new Uri("ftp://" + ServerIP + "/" + FileSource);
                if (CreateDirectory(uri, pFtpUserID, pFtpPW))
                {
                    //检测下一级目录是否存在
                    uri = new Uri("ftp://" + ServerIP + "/" + FileSource + "/" + FileCategory + "/");
                    if (!DirectoryIsExist(uri, pFtpUserID, pFtpPW))
                    {
                        //创建目录
                        uri = new Uri("ftp://" + ServerIP + "/" + FileSource + "/" + FileCategory);
                        if (CreateDirectory(uri, pFtpUserID, pFtpPW))
                        {
                            return true;
                        }
                        else { XtraMessageBox.Show("创建目录:{0}失败", FileCategory); return false; }
                    }
                    else
                    {
                        return true;
                    }
                }
                else { XtraMessageBox.Show("创建目录:{0}失败", FileSource); return false; }
            }
            else
            {
                //检测下一级目录是否存在
                uri = new Uri("ftp://" + ServerIP + "/" + FileSource + "/" + FileCategory + "/");
                if (!DirectoryIsExist(uri, pFtpUserID, pFtpPW))
                {
                    //创建目录
                    uri = new Uri("ftp://" + ServerIP + "/" + FileSource + "/" + FileCategory);
                    if (CreateDirectory(uri, pFtpUserID, pFtpPW))
                    {
                        return true;
                    }
                    else { XtraMessageBox.Show("创建目录:{0}失败", FileCategory); return false; }
                }
                else
                {
                    return true;
                }
            }
        }
        /// <summary>
        /// ftp创建目录(创建文件夹)
        /// </summary>
        /// <param name="IP">IP服务地址</param>
        /// <param name="UserName">登陆账号</param>
        /// <param name="UserPass">密码</param>
        /// <param name="FileSource"></param>
        /// <param name="FileCategory"></param>
        /// <returns></returns>
        public static bool CreateDirectory(Uri IP, string UserName, string UserPass)
        {
            try
            {
                FtpWebRequest FTP = (FtpWebRequest)FtpWebRequest.Create(IP);
                FTP.Credentials = new NetworkCredential(UserName, UserPass);
                FTP.Proxy = null;
                FTP.KeepAlive = false;
                FTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                FTP.UseBinary = true;
                FtpWebResponse response = FTP.GetResponse() as FtpWebResponse;
                response.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 检测目录是否存在
        /// </summary>
        /// <param name="pFtpServerIP"></param>
        /// <param name="pFtpUserID"></param>
        /// <param name="pFtpPW"></param>
        /// <returns>false不存在,true存在</returns>
        public static bool DirectoryIsExist(Uri pFtpServerIP, string pFtpUserID, string pFtpPW)
        {
            string[] value = GetFileList(pFtpServerIP, pFtpUserID, pFtpPW);
            if (value == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        public static string[] GetFileList(Uri pFtpServerIP, string pFtpUserID, string pFtpPW)
        {
            StringBuilder result = new StringBuilder();
            try
            {
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(pFtpServerIP);
                reqFTP.UseBinary = true;
                reqFTP.Credentials = new NetworkCredential(pFtpUserID, pFtpPW);
                reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

WebResponse response = reqFTP.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string line = reader.ReadLine();
                while (line != null)
                {
                    result.Append(line);
                    result.Append("\n");
                    line = reader.ReadLine();
                }
                reader.Close();
                response.Close();
                return result.ToString().Split('\n');
            }
            catch
            {
                return null;
            }
        }

==========================================================

C#对FTP的操作(上传,下载,重命名文件,删除文件,文件存在检查)

http://blog.csdn.net/hejialin666/article/details/3522815

  • using System;
  • using System.Collections.Generic;
  • using System.Text;
  • using System.Net;
  • using System.Data;
  • using System.IO;
  • using System.ComponentModel;
  • namespace Common
  • {
  • public class FTPClient
  • {
  • private string ftpServerIP = String.Empty;
  • private string ftpUser = String.Empty;
  • private string ftpPassword = String.Empty;
  • private string ftpRootURL = String.Empty;
  • public FTPClient(string url, string userid,string password)
  • {
  • this.ftpServerIP = ftp的IP地址;
  • this.ftpUser = 用户名;
  • this.ftpPassword = 密码;
  • this.ftpRootURL = "ftp://" + url + "/";
  • }
  • /// <summary>
  • /// 上传
  • /// </summary>
  • /// <param name="localFile">本地文件绝对路径</param>
  • /// <param name="ftpPath">上传到ftp的路径</param>
  • /// <param name="ftpFileName">上传到ftp的文件名</param>
  • public bool fileUpload(FileInfo localFile, string ftpPath, string ftpFileName)
  • {
  • bool success = false;
  • FtpWebRequest ftpWebRequest = null;
  • FileStream localFileStream = null;
  • Stream requestStream = null;
  • try
  • {
  • string uri = ftpRootURL + ftpPath + ftpFileName;
  • ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  • ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
  • ftpWebRequest.UseBinary = true;
  • ftpWebRequest.KeepAlive = false;
  • ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
  • ftpWebRequest.ContentLength = localFile.Length;
  • int buffLength = 2048;
  • byte[] buff = new byte[buffLength];
  • int contentLen;
  • localFileStream = localFile.OpenRead();
  • requestStream = ftpWebRequest.GetRequestStream();
  • contentLen = localFileStream.Read(buff, 0, buffLength);
  • while (contentLen != 0)
  • {
  • requestStream.Write(buff, 0, contentLen);
  • contentLen = localFileStream.Read(buff, 0, buffLength);
  • }
  • success = true;
  • }
  • catch (Exception)
  • {
  • success = false;
  • }
  • finally
  • {
  • if (requestStream != null)
  • {
  • requestStream.Close();
  • }
  • if (localFileStream != null)
  • {
  • localFileStream.Close();
  • }
  • }
  • return success;
  • }
  • /// <summary>
  • /// 上传文件
  • /// </summary>
  • /// <param name="localPath">本地文件地址(没有文件名)</param>
  • /// <param name="localFileName">本地文件名</param>
  • /// <param name="ftpPath">上传到ftp的路径</param>
  • /// <param name="ftpFileName">上传到ftp的文件名</param>
  • public bool fileUpload(string localPath, string localFileName, string ftpPath, string ftpFileName)
  • {
  • bool success = false;
  • try
  • {
  • FileInfo localFile = new FileInfo(localPath + localFileName);
  • if (localFile.Exists)
  • {
  • success = fileUpload(localFile, ftpPath, ftpFileName);
  • }
  • else
  • {
  • success = false;
  • }
  • }
  • catch (Exception)
  • {
  • success = false;
  • }
  • return success;
  • }
  • /// <summary>
  • /// 下载文件
  • /// </summary>
  • /// <param name="localPath">本地文件地址(没有文件名)</param>
  • /// <param name="localFileName">本地文件名</param>
  • /// <param name="ftpPath">下载的ftp的路径</param>
  • /// <param name="ftpFileName">下载的ftp的文件名</param>
  • public bool fileDownload(string localPath, string localFileName, string ftpPath, string ftpFileName)
  • {
  • bool success = false;
  • FtpWebRequest ftpWebRequest = null;
  • FtpWebResponse ftpWebResponse = null;
  • Stream ftpResponseStream = null;
  • FileStream outputStream = null;
  • try
  • {
  • outputStream = new FileStream(localPath + localFileName, FileMode.Create);
  • string uri = ftpRootURL + ftpPath + ftpFileName;
  • ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  • ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
  • ftpWebRequest.UseBinary = true;
  • ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
  • ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
  • ftpResponseStream = ftpWebResponse.GetResponseStream();
  • long contentLength = ftpWebResponse.ContentLength;
  • int bufferSize = 2048;
  • byte[] buffer = new byte[bufferSize];
  • int readCount;
  • readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
  • while (readCount > 0)
  • {
  • outputStream.Write(buffer, 0, readCount);
  • readCount = ftpResponseStream.Read(buffer, 0, bufferSize);
  • }
  • success = true;
  • }
  • catch (Exception)
  • {
  • success = false;
  • }
  • finally
  • {
  • if (outputStream != null)
  • {
  • outputStream.Close();
  • }
  • if (ftpResponseStream != null)
  • {
  • ftpResponseStream.Close();
  • }
  • if (ftpWebResponse != null)
  • {
  • ftpWebResponse.Close();
  • }
  • }
  • return success;
  • }
  • /// <summary>
  • /// 重命名
  • /// </summary>
  • /// <param name="ftpPath">ftp文件路径</param>
  • /// <param name="currentFilename"></param>
  • /// <param name="newFilename"></param>
  • public bool fileRename(string ftpPath, string currentFileName, string newFileName)
  • {
  • bool success = false;
  • FtpWebRequest ftpWebRequest = null;
  • FtpWebResponse ftpWebResponse = null;
  • Stream ftpResponseStream = null;
  • try
  • {
  • string uri = ftpRootURL + ftpPath + currentFileName;
  • ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  • ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
  • ftpWebRequest.UseBinary = true;
  • ftpWebRequest.Method = WebRequestMethods.Ftp.Rename;
  • ftpWebRequest.RenameTo = newFileName;
  • ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
  • ftpResponseStream = ftpWebResponse.GetResponseStream();
  • }
  • catch (Exception)
  • {
  • success = false;
  • }
  • finally
  • {
  • if (ftpResponseStream != null)
  • {
  • ftpResponseStream.Close();
  • }
  • if (ftpWebResponse != null)
  • {
  • ftpWebResponse.Close();
  • }
  • }
  • return success;
  • }
  • /// <summary>
  • /// 消除文件
  • /// </summary>
  • /// <param name="filePath"></param>
  • public bool fileDelete(string ftpPath, string ftpName)
  • {
  • bool success = false;
  • FtpWebRequest ftpWebRequest = null;
  • FtpWebResponse ftpWebResponse = null;
  • Stream ftpResponseStream = null;
  • StreamReader streamReader = null;
  • try
  • {
  • string uri = ftpRootURL + ftpPath + ftpName;
  • ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
  • ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
  • ftpWebRequest.KeepAlive = false;
  • ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile;
  • ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();
  • long size = ftpWebResponse.ContentLength;
  • ftpResponseStream = ftpWebResponse.GetResponseStream();
  • streamReader = new StreamReader(ftpResponseStream);
  • string result = String.Empty;
  • result = streamReader.ReadToEnd();
  • success = true;
  • }
  • catch (Exception)
  • {
  • success = false;
  • }
  • finally
  • {
  • if (streamReader != null)
  • {
  • streamReader.Close();
  • }
  • if (ftpResponseStream != null)
  • {
  • ftpResponseStream.Close();
  • }
  • if (ftpWebResponse != null)
  • {
  • ftpWebResponse.Close();
  • }
  • }
  • return success;
  • }
  • /// <summary>
  • /// 文件存在检查
  • /// </summary>
  • /// <param name="ftpPath"></param>
  • /// <param name="ftpName"></param>
  • /// <returns></returns>
  • public bool fileCheckExist(string ftpPath, string ftpName)
  • {
  • bool success = false;
  • FtpWebRequest ftpWebRequest = null;
  • WebResponse webResponse = null;
  • StreamReader reader = null;
  • try
  • {
  • string url = ftpRootURL + ftpPath;
  • ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
  • ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPassword);
  • ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;
  • ftpWebRequest.KeepAlive = false;
  • webResponse = ftpWebRequest.GetResponse();
  • reader = new StreamReader(webResponse.GetResponseStream());
  • string line = reader.ReadLine();
  • while (line != null)
  • {
  • if (line == ftpName)
  • {
  • success = true;
  • break;
  • }
  • line = reader.ReadLine();
  • }
  • }
  • catch (Exception)
  • {
  • success = false;
  • }
  • finally
  • {
  • if (reader != null)
  • {
  • reader.Close();
  • }
  • if (webResponse != null)
  • {
  • webResponse.Close();
  • }
  • }
  • return success;
  • }
  • }
  • }

C# ftp 上传、下载、删除的更多相关文章

  1. java FTP 上传下载删除文件

    在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件 ...

  2. 通过代码链接ftp上传下载删除文件

    因为我的项目是Maven项目,首先要导入一个Maven库里的包:pom.xml <dependency>            <groupId>com.jcraft</ ...

  3. JAVA 实现FTP上传下载&lpar;sun&period;net&period;ftp&period;FtpClient&rpar;

    package com.why.ftp; import java.io.DataInputStream; import java.io.File; import java.io.FileInputSt ...

  4. windows系统下ftp上传下载和一些常用命令

    先假设一个ftp地址 用户名 密码 FTP Server: home4u.at.china.com User: yepanghuang Password: abc123 打开windows的开始菜单, ...

  5. windows下ftp上传下载和一些常用命令

    先假设一个ftp地址 用户名 密码 FTP Server: home4u.at.china.com User: yepanghuang Password: abc123 打开windows的开始菜单, ...

  6. FTP上传下载工具&lpar;FlashFXP&rpar; v5&period;5&period;0 中文版

    软件名称: FTP上传下载工具(FlashFXP) 软件语言: 简体中文 授权方式: 免费试用 运行环境: Win 32位/64位 软件大小: 7.4MB 图片预览: 软件简介: FlashFXP 是 ...

  7. 高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)

    前言 最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种. 第一种是单例模式的类. 第二种是另外定义一个Service,直接通过Service来实现ftp的上 ...

  8. C&num; -- FTP上传下载

    C# -- FTP上传下载 1. C#实现FTP下载 private static void TestFtpDownloadFile(string strFtpPath, string strFile ...

  9. Java&period;ftp上传下载

    1:jar的maven的引用: 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...

  10. python之实现ftp上传下载代码&lpar;含错误处理&rpar;

    # -*- coding: utf-8 -*- #python 27 #xiaodeng #python之实现ftp上传下载代码(含错误处理) #http://www.cnblogs.com/kait ...

随机推荐

  1. HTML5 使用application cache 接口实现离线数据缓存

    1.配置缓存文件 cache manifest MIME TYPE:text/cache-manifest文件名称:name.appcache作用:用于配置需要缓存的文件 2.使用方法 在服务器上添加 ...

  2. DataTable select根据条件取值

    1.封装独立方法 // 执行DataTable中的查询返回新的DataTable /// </summary> /// <param name="dt">源 ...

  3. javascript之流程控制 和函数的容易忽略点

    1.流程控制 1> for in  仅用于 对象的遍历: var box={ "name":'小红', 'age':18, 'height':165 }; for(var b ...

  4. 算法导论学习-binary search tree

    1. 概念: Binary-search tree(BST)是一颗二叉树,每个树上的节点都有<=1个父亲节点,ROOT节点没有父亲节点.同时每个树上的节点都有[0,2]个孩子节点(left ch ...

  5. IOS UITableView NSIndexPath属性讲解

    IOS UITableView NSIndexPath属性讲解   查看UITableView的帮助文档我们会注意到UITableView有两个Delegate分别为:dataSource和deleg ...

  6. poj 3368 Frequent values(段树)

    Frequent values Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 13516   Accepted: 4971 ...

  7. Android 应用程序窗口显示状态操作(requestWindowFeature&lpar;&rpar;的应用)

     我们在开发程序是常常会须要软件全屏显示.自己定义标题(使用button等控件)和其它的需求,今天这一讲就是怎样控制Android应用程序的窗口显示. 首先介绍一个重要方法那就是requestWi ...

  8. 2014阿里实习生面试题——mysql如何实现的索引

    这是2014北京站的两副面孔阿里实习生问题扯在一起: 在MySQL中.索引属于存储引擎级别的概念,不同存储引擎对索引的实现方式是不同的,比方MyISAM和InnoDB存储引擎. MyISAM索引实现: ...

  9. iOS数据持久化之数据库:SQLite和FMDB

    SQLite: SQLite是一款轻量级型的数据库,资源占用少.性能良好和零管理成本,具有零配置(无需安装和管理配置).独立(没有额外依赖).储存在单一磁盘文件中的一个完整的数据库.源码完全的开源.比 ...

  10. MongoDB--GridFS 文件存储系统

    GridFS是Mongo的一种专门用存储小型文件的功能. 使用于下列场景: 1.写入文件:mongofiles put 文件路径 注意,当前mongo实例链接的哪个库,将写文件在哪个实例里面的grid ...