当前位置:主页 > 软件编程 > .NET代码 >

C#使用FtpWebRequest与FtpWebResponse完成FTP操作

时间:2023-01-21 09:41:25 | 栏目:.NET代码 | 点击:

一、WebRequestMethods.Ftp类:

表示可与 FTP 请求一起使用的 FTP 协议方法的类型。

二、上传文件:

OpenFileDialog opFilDlg = new OpenFileDialog();
if (opFilDlg.ShowDialog() == DialogResult.OK)
{   ftp = new YBBFTPClass("hz.a.cn", "", "csp", "welcome", 0);
    ftp.UploadFile(opFilDlg.FileName);
    MessageBox.Show("上传成功");
}
/// <summary>
/// 文件上传
/// </summary>
/// <param name="filename">本地文件路径</param>
public void UploadFile(string filename)
{
    FileInfo fileInf = new FileInfo(filename);
    string uri = "ftp://" + RemoteHost + "/" + fileInf.Name;
    FtpWebRequest reqFTP;

    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + RemoteHost + "/" + fileInf.Name));// 根据uri创建FtpWebRequest对象
    reqFTP.Credentials = new NetworkCredential(RemoteUser, RemotePass);    // ftp用户名和密码
    reqFTP.KeepAlive = false;    // 默认为true,连接不会被关闭, 在一个命令之后被执行
    reqFTP.Method = WebRequestMethods.Ftp.UploadFile;    // 指定执行什么命令
    reqFTP.UseBinary = true;   // 指定数据传输类型
    reqFTP.ContentLength = fileInf.Length;    // 上传文件时通知服务器文件的大小

    int contentLen;
    FileStream fileStream = fileInf.OpenRead(); // 打开一个文件读取内容到fileStream中
    contentLen = fileStream.Read(buffer, 0, buffer.Length); ;//从fileStream读取数据到buffer中

    Stream requestStream = reqFTP.GetRequestStream();
    // 流内容没有结束
    while (contentLen != 0)
    {
        requestStream.Write(buffer, 0, contentLen);// 把内容从buffer 写入 requestStream中,完成上传。
        contentLen = fileStream.Read(buffer, 0, buffer.Length);
    }

    // 关闭两个流
    requestStream.Close();
    //uploadResponse = (FtpWebResponse)reqFTP.GetResponse();
    fileStream.Close();
}

三、下载文件

1、核心代码

/// <summary>
/// 下载文件
/// </summary>
/// <param name="filePath">本地目录</param>
/// <param name="fileName">远程路径</param>
public void DownloadFile(string filePath, string fileName)
{
    FtpWebRequest reqFTP;
    try
    {
        FileStream fileStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);

        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + RemoteHost + "/" + fileName));
        reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
        reqFTP.UseBinary = true;
        reqFTP.Credentials = new NetworkCredential(RemoteUser, RemotePass);

        FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
        Stream responseStream = response.GetResponseStream();//从ftp响应中获得响应流

        //long cl = response.ContentLength;
        byte[] buffer = new byte[1024];
        int readCount;

        readCount = responseStream.Read(buffer, 0, buffer.Length);//从ftp的responseStream读取数据到buffer中
        while (readCount > 0)
        {
            fileStream.Write(buffer, 0, readCount);//从buffer读取数据到fileStream中,完成下载
            readCount = responseStream.Read(buffer, 0, buffer.Length);
        }

        responseStream.Close();
        fileStream.Close();
        response.Close();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

2、winform:

FolderBrowserDialog fldDlg = new FolderBrowserDialog();
if (txtUpload.Text.Trim().Length > 0)
{
    if (fldDlg.ShowDialog() == DialogResult.OK)
    {
        ftp.DownloadFile(fldDlg.SelectedPath, txtUpload.Text.Trim());
        MessageBox.Show("下载成功");
    }
}
else
{
    MessageBox.Show("Please enter the File name to download");
}

3、webform弹出下载提示:

FtpClient _client = new FtpClient();
Stream stream = _client.OpenRead(FtpFilePath, FtpDataType.Binary);

string FtpFilePath = Request.QueryString["FilePath"];
string _fname = Path.GetFileName(FtpFilePath);
Response.ContentType = "application/" + _fname.Split('.')[1];
Response.AddHeader("Content-disposition", "attachment; filename=" + _fname);

byte[] buffer = new byte[10240];
int readCount;
do
{
    readCount = stream.Read(buffer, 0, buffer.Length);
    Response.OutputStream.Write(buffer, 0, readCount);//持续写入流
} while (readCount != 0);

Response.OutputStream.Write(buffer, 0, buffer.Length);

Response.End();

四、删除文件

string uri = "ftp://" + RemoteHost + "/" + fileName;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + RemoteHost + "/" + fileName));

reqFTP.Credentials = new NetworkCredential(RemoteUser, RemotePass);
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();

完整代码参考:

https://www.jb51.net/article/119779.htm

您可能感兴趣的文章:

相关文章