Ftp上传下载 C#

public class MyFtpClass
    {
        private readonly string _destIp;
        private readonly string _userName;
        private readonly string _password;
        public MyFtpClass(string desIp, string userName, string passowrd)
        {
            this._destIp = desIp;
            this._userName = userName;
            this._password = passowrd;
        }
        private FtpWebRequest OpenRequest(Uri uri,string ftpMethod)
        {
            FtpWebRequest request = WebRequest.Create(uri) as FtpWebRequest;
            if (request != null)
            {
                request.Credentials = new NetworkCredential(_userName, _password);
                request.UseBinary = true;
                request.Method = ftpMethod;
                return request;
            }
            else
            {
                return null;
            }

        }
        private FtpWebResponse OpenResponse(Uri uri, string ftpMethod)
        {
            FtpWebRequest request= this.OpenRequest(uri, ftpMethod);
            if (request != null)
            {
                FtpWebResponse response = request.GetResponse() as FtpWebResponse;
                return response;
            }
            else
            {
                return null;
            }

        }
        /// <summary>
        /// 要上传的本地文件路径
        /// </summary>
        /// <param name="uploadFilePath">形如:D:\\folder1\\2.jpg </param>
        /// <param name="desName">形如:123.jpg 或 subFolder1/123.jpg</param>
        /// <returns></returns>
        public bool Upload(string uploadFilePath, string desName)
        {
            Stream requestStream = null;
            FtpWebResponse response = null;
            try
            {
                Uri uri = new Uri(string.Format("ftp://{0}/{1}", _destIp, desName));
                FtpWebRequest request = OpenRequest(uri, WebRequestMethods.Ftp.UploadFile);
                requestStream = request.GetRequestStream();

                FileStream fs = File.Open(uploadFilePath, FileMode.Open);
                byte[] buff = new byte[1024];
                int buffRead = 0;
                while (true)
                {
                    int n = fs.Read(buff, buffRead, buff.Length);
                    if (n == 0)
                    {
                        break;
                    }
                    //把文件流写入请求流
                    requestStream.Write(buff, 0, n);
                }

                response = (FtpWebResponse)request.GetResponse();
                return true;
            }
            catch (Exception)
            {
                throw new Exception("上传文件失败!");
            }
            finally
            {
                requestStream.Close();
                response.Close();
            }

        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="serverFileName">要下载的文件名。形如:123.jpg 或 subFolder1/123.jpg</param>
        /// <param name="localPath">下载至本地的路径。形如: D:\\a\\b\\</param>
        /// <param name="localName">保存在本地的名称。形如:3.jpg</param>
        /// <returns></returns>
        public bool Download(string serverFileName, string localPath, string localName)
        {
            Stream responseStream=null;
            FileStream fileStream=null;
            try
            {
                Uri uri = new Uri(string.Format("ftp://{0}/{1}", _destIp, serverFileName));
                FtpWebResponse downloadResponse = OpenResponse(uri, WebRequestMethods.Ftp.DownloadFile);
                responseStream = downloadResponse.GetResponseStream();
                fileStream = File.Create(localPath + localName);
                byte[] buffer = new byte[1024];
                while (true)
                {
                    var bytesRead = responseStream.Read(buffer, 0, buffer.Length);
                    if (bytesRead == 0)
                        break;
                    //把响应流写入文件
                    fileStream.Write(buffer, 0, bytesRead);
                }

                return true;
            }
            catch
            {
                throw new Exception("获取下载文件失败!");
            }
            finally
            {
                fileStream.Close();
                responseStream.Close();
            }
        }
    }
需要注意的流文件的读出和写入问题:例如,
int n = fs.Read(buff, buffRead, buff.Length);bufferRead和buff.Length指的是数组buff的索引以及长度。流文件fs会自动维护一个指针Position,每当read n个字节时,会自动向后移动n个字节。
fileStream.Write(buffer, 0, bytesRead);是同样的道理。
 
时间: 2024-10-27 19:04:26

Ftp上传下载 C#的相关文章

python之实现ftp上传下载代码(含错误处理)

# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之实现ftp上传下载代码(含错误处理) #http://www.cnblogs.com/kaituorensheng/p/4480512.html#_label2 import ftplib import socket import os def ftpconnect(ftp_info): try: ftp = ftplib.FTP(ftp_info[0]) except (socket.er

python之模块ftplib(实现ftp上传下载代码)

# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之模块ftplib(实现ftp上传下载代码) #需求:实现ftp上传下载代码(不含错误处理) from ftplib import FTP def ftpconnect(): ftp_server='ftp.python.org' ftp=FTP() ftp.set_debuglevel(2)#打开调式级别2 ftp.connect(ftp_server,21) ftp.login('',''

python网络编程socket模块实现ftp上传下载

本实验实现ftp上传文件下载文件功能,并具有校验文件完整性,打印进度条功能, 主要练习socket,struct模块. ftp用户文件存放在user.json文件中 user.json文件内容 {"lisi": "abcdef", "hyh": "123456"} ftp客户端脚本ftpclient.py #!/usr/bin/python # --*-- coding: utf-8 --*-- import socket i

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

先假设一个ftp地址 用户名 密码 FTP Server: home4u.at.china.com User: yepanghuang Password: abc123 打开windows的开始菜单,执行“运行”命令,在对话框中输入ftp,按下“确定”按钮将会切换至DOS窗口,出现命令提示符 ftp>键入命令连接FTP服务器: ftp> open home4u.at.china.com (回车) 稍等片刻,屏幕提示连接成功: ftp> connected to home4u.china.

简单的FTP上传下载(java实现)

/** *阅读前请自己在win7上建立FTP主机 *具体步骤如:http://jingyan.baidu.com/article/574c5219d466c36c8d9dc138.html * 然后将以下FTP,username,password分别改成你的FTP ip地址 用户名 密码即可 * 本例子用了apche的commons-net-3.3.jar以方便FTP的访问 请手动buid -path * 待完成版 刷新按钮 登录 都还没有做 而且上传 下载 完成后都需要重新运行 * 2014-

C# FTP 上传 下载(汇总)

1.C# 上传下载ftp(支持断点续传) 2. C# FTP上传下载(支持断点续传)

java ftp上传下载

/** * Description: 从FTP服务器下载文件 * @param url FTP服务器hostname * @param port FTP服务器端口 * @param username FTP登录账号 * @param password FTP登录密码 * @param remotePath FTP服务器上的相对路径 * @param fileName 要下载的文件名 * @param localPath 下载后保存到本地的路径 * @return */ public static

FTP 上传下载工具类

import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.SocketException; import o

java做的比较完善的FTP上传下载文件服务器源码

Filename: ftp.java Author: leetsing(elove) Create date: 2004-08-30 Use: connect to FTP server,then upload and download file Modify date: 2004-09-05 add to upload file 2004-09-13 add to download file Copy right: Magisky Media Technology Co.,Ltd. *****

java ftp 上传下载工具类

1 package com.mohecun.utils; 2 3 import java.io.File; 4 import java.io.FileInputStream; 5 import java.io.FileNotFoundException; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.io.InputStream; 9 import java.io.OutputStre