FTP UPLOAD

2023-11-17

First, you should add the following directives:

Listing 1 - Directives

using System.Net;
using System.IO;

The following steps can be considered as a generic procedure of getting an FTP request executed using FtpWebRequest object.

1.    Create an FtpWebRequest object over an ftp server URI.

2.    Set the FTP method to execute (upload, download, etc.).

3.    Set the options (SSL support, transfer as binary/not etc.) for the FTP webrequest.

4.    Set the login credentials (username, password).

5.    Execute the request.

6.    Receive the response stream (if required).

7.    Close the FTP Request, in addition to any open streams.

One point to watch out while coding for any FTP application is to have the settings for the ftp request proper to suit the ftp server and its specific configurations. FtpWebRequest object exposes many properties to have these settings in place.

The sample for the upload functionality is as follows:

First a URI is created which represents the FTP address along with the filename (directory structure included). This URI is used to create the FtpWebRequest instance.
Then properties of the FtpWebRequest object are set, which determines the settings for the ftp request. Some of its important properties are:

Credentials - Specifies the username and password to login to the FTP server.

KeepAlive - Specifies if the control connection should be closed or not after the request is completed. By default it is set to true.

UseBinary - Denotes the datatype for file transfers. The 2 modes of file transfer in this case are Binary and ASCII. At bit level both vary in the 8th bit of a byte. ASCII uses 8th bit as insignificant bit for error control, where as, for binary all the 8 bits are significant. So take care when you go for the ASCII transmission. To be simple, all those files that open and read well in notepad are safe as ASCII. Executables, formatted docs, etc. should be sent using binary mode. BTW sending ASCII files as binary works fine most of the time.

UsePassive - Specifies to use either active or passive mode. Earlier active FTP worked fine with all clients, but now a days as most of the random ports will blocked by firewall and the active mode may fail. The passive FTP is helpful in this case, but still it causes issues at the server. The higher ports requested by client on server may also be blocked by firewall. But since FTP servers will need to make their servers accessible to the greatest number of clients, they will almost certainly need to support passive FTP. The reason why passive mode is considered safe is that it ensures all data flow initiation comes from inside (client) the network rather than from the outside (server).

Contentlength - Setting this property is useful for the server we request to, but is not of much use for us (client) because FtpWebRequest usually ignores this property value, so it will not be available for our use in most of the cases. If we set this property, the FTP server will get an idea in advance about the size of the file it should expect (in case of upload).

Method - Denotes what action (command) to take in the current request (upload, download, filelist, etc.).  It is set a value defined in the WebRequestMethods.Ftp structure.

Listing 2 - Upload

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

Above is a sample code for FTP Upload (PUT). The underlying sub command used is STOR. Here an FtpWebRequest object is made for the specified file on the ftp server.
Different properties are set for the request, namely Credentials, KeepAlive Method, UseBinary, ContentLength.

The file in our local machine is opened and the contents are written to the FTP request stream. Here a buffer of size 2kb is used as an appropriate size suited for upload of larger or smaller files.

Listing 3 - Download

private void Download(string filePath, string fileName)
{
    FtpWebRequest reqFTP;
    try
    {
        //filePath = <<The full path where the file is to be created. the>>, 
        //fileName = <<Name of the file to be createdNeed not name on FTP server. name name()>>
        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);
    }
}

Above is a sample code for Download of file from the FTP server. Unlike the Upload functionality described above, Download would require the response stream, which will contain the content of the file requested.

Here the file to download is specified as part of the Uri which in turn is used for the creation of the FtpWebRequest object. To "GET" the file requested, get the response of the FtpWebRequest object using GetResponse() method. This new response object built provides the response stream, which contain the file content as stream that you can easily convert to a file stream to get the file in place.

Note: We have the flexibility to set the location and name of the file under which it is to be saved on our local machine.

Listing 4 – Retrieve Filelist on FTP Server

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());
 
        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;
    }
}

Above is a sample block of code for getting the file list on the ftp server. The Uri is built specifying the FTP server address/name and the required path if any. In the above example the root folder is specified for the creation of the FtpWebRequest object. Here the response stream is used for the creation of a StreamReader object, which has the whole list of file names on the server separated by "\r\n." this is the newline and carriagereturn together. You can get the whole file list ("\r\n" separated) using the ReadToEnd() method of the StreamReader object. The above implementation reads each file name and creates a StringBuilder object by appending each file name. The resultant StringBuilder object is split into a string array and returned. I am sure there are better ways to do it like removing the whole '\r" instances from the whole list (returned by <<StreamReader>>.ReadToEnd())) and split the resultant string uisng "\n" delimiter. Anyway, I did not want to spend more of my energy and time pondering over it.

The implementations for Rename, Delete, GetFileSize, FileListDetails, MakeDir are very similar to the above pieces of code and the attached code is easily comprehensible.

Note: For Renaming, the new name can be assigned to the RenameTo property of FtpWebRequest object. For MakeDirectory, the name of the new directory can be specified as part of the Uri used to create FtpWebRequest object.

转载于:https://www.cnblogs.com/skyado/archive/2010/03/07/1680472.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

FTP UPLOAD 的相关文章

  • FTP UPLOAD

    First you should add the following directives Listing 1 Directives using System Net using System IO The following steps
  • sublime 代码提示插件

    Sublime Text 2是个相当棒的编辑器 这一点异次元和Lucifr的文章都介绍的很充分了 用了一段时间觉得Sublime确实 性感 而 强大 只是Sublime Text 2毕竟是一款 编辑器 而非 集成开发环境 IDE 在很多ID
  • 开发工具之 Snipaste(超级截图工具)

    snipaste工具是一款开源免费的超级截图工具 这里小编强烈推荐此工具的使用 前言 当你使用ALT TAB习惯性的来回切屏的时候 其实在这个过程中 仔细想想是不是比较累 这样子做久了很容易导致疲劳 所以小编强推贴图功能 好了废话不多说 直
  • ApiPost 开源接口调试工具使用大全

    ApiPost使用 简介 接口调试 API请求参数 Header 参数 Query 参数 Body 参数 API 请求响应 返回Headers 响应结果分屏展示 生成调试代码 参数 全局参数 目录参数 参数的优先级 变量 环境变量 环境变量
  • 一个简单的WebService实例

    WebService在 NET平台下的作用是在不同应用程序间共享数据与数据交换 要达到这样的目标 Web services要使用两种技术 XML 标准通用标记语言下的一个子集 XML是在web上传送结构化数据的伟大方式 Web servic
  • Docker客户端连接Docker Daemon的方式

    Docker为C S架构 服务端为docker daemon 客户端为docker service 支持本地unix socket域套接字通信与远程socket通信 默认为本地unix socket通信 要支持远程客户端访问需要做如下设置
  • mac xmind

    1 首先要安装包 XMind For Mac 本人下载的这个版本xmind8update9 2 下载破解包 XMindCrack jar 链接 https pan baidu com s 1jqpodMvKQTNQyenAIy0Y3w 密码
  • maven项目debug查看依赖包源代码办法

    默认的maven工程 好像很难加载依赖的源代码 办法如下 maven调试时 无法进入源码 办法一 在debug配置里面 找到source 把带source的jar包 放进去 添加的时候 选add 再选external archive 这里要
  • 设计模式三: 代理模式(Proxy) -- JDK的实现方式

    简介 代理模式属于行为型模式的一种 控制对其他对象的访问 起到中介作用 代理模式核心角色 真实角色 代理角色 按实现方式不同分为静态代理和动态代理两种 意图 控制对其它对象的访问 类图 实现 JDK自带了Proxy的实现 下面我们先使用JD
  • [转] 解读IntelliJ IDEA的优缺点

    昨天去TW参加了pre class 就是类似于新员工入职前的培训 有很多很cool的东西 给我印象最深的就是IntelliJ IDEA了 coder么 刚才在网上搜了搜 发现很少有她的介绍资料 所以贴过来一个让大家看看 文章中有一句话值得大
  • Docker下使用jstat查看jvm的GC信息

    Jstat指令 jstat命令命令格式 jstat Options vmid interval count 参数说明 Options 选项 我们一般使用 gcutil 查看gc情况 vmid VM的进程号 即当前运行的java进程号 int
  • 将onnx的静态batch改为动态batch及修改输入输出层的名称

    文章目录 背景 操作 修改输入输出层 修改输入输出层名称 完整代码 背景 在模型的部署中 为了高效利用硬件算力 常常会需要将多个输入组成一个batch同时输入网络进行推理 这个batch的大小根据系统的负载或者摄像头的路数时刻在变化 因此网
  • <Linux开发>linux开发工具- 之-开发使用linux命令记录

    Linux开发 linux开发工具 之 开发使用linux命令记录 本文章主要记录开发过程中涉及使用的linux命令 1 查看磁盘大小分区情况 命令 df hl 可查看分区的路径 及空间大小使用情况 以及挂在点位置 2 查看指定目录文件的大
  • 蚂蚁笔记私有部署

    说明 其实官方的教程中已经写得很清楚了 我写这个主要是为了记录一下我自己当时安装的过程 方便后续查询 官方文档请查阅 https github com leanote leanote wiki 环境要求 CentOS6 5 Nginx Mo
  • python中,获取字符串的长度

    说明 与其他的语言一样 有时候需要查看或者说计算字符串的长度 在此记录下python中通过哪个函数实现 操作过程 1 通过len 函数返回字符串的长度 gt gt gt text python gt gt gt len text 6 gt
  • IAR个人常用配置

    IAR个人常用配置 文章目录 IAR个人常用配置 1 设置 2 设置tab和indent为4空格 3 设置编码为UTF 8 4 自动缩进设置 5 修改背景颜色和字体 6 修改全局搜索快捷键 1 设置 Tools gt Options 2 设
  • Sublime Text 常用快捷键

    文章目录 通用 General 编辑 Editing 选择 Selecting 查找 替换 Finding Replacing 跳转 Jumping 窗口 Window 屏幕 Screen 工欲善其事 必先利其器 本文收集 Sublime
  • Matplotlib画条形图和柱形图并添加数据标注

    这里放上我比较喜欢的一种条形图设置 使用的是之前爬取的重庆地区链家二手房数据 数据如下 链接 https pan baidu com s 17CMwUAdseO8tJWHEQiA8 A 提取码 dl2g import pandas as p
  • java.lang.IllegalAccessError: class javax.activation.SecuritySupport12 cannot access its superclass

    最近加入新的项目组 eclipse tomcat7 spring ibatis restful 遇到了这样的问题 说是不能访问父类 我一开始以为是版本的原因 但是久经更改 错误依然 实在累了 最终的解决办法是我把SecuritySuppor
  • 4个开源的Java代码静态分析工具

    1 PMD PMD是一款采用BSD协议发布的Java程序代码检查工具 该工具可以做到检查Java代码中是否含有未使用的变量 是否含有空的抓取块 是否含有不必要的对象等 该软件功能强大 扫描效率高 是Java程序员debug的好帮手 PMD支

随机推荐

  • Oracle---day01

    一 简单查询语句 1 去重查询 和mysql的一样 select distinct job from emp select distinct job deptno from emp 去除job相等且deptno相等的结果 2 查询员工年薪
  • Hanlp本地化安装

    环境说明 系统 centos7 x python版本 3 9 0 这里安装完整版本hanlp full 精简版会有不少问题出现 没有找到解决方案 官网安装地址 https hanlp hankcs com install html 2 x
  • HTML简介

    目录 话不多说 先上一个HELLO WORLD 什么是 HTML HTML 标签 HTML 文档 网页 例子解释 话不多说 先上一个HELLO WORLD h1 我的第一个标题 h1 p 我的第一个段落 p 什么是 HTML HTML 是用
  • octave 机器学习_使用Octave开发机器学习算法

    octave 机器学习 Octave is an open source high level programming language designed to perform efficient numerical computation
  • 深度学习大数据

    CAFFE深度学习交流群 532629018 国内数据 链接 http pan baidu com s 1i5nyjBn 密码 26bm 好玩的数据集 链接 http pan baidu com s 1bSDIEi 密码 25zr 微软数据
  • java调用自己写的类型_Java基础——自定义类的使用

    自定义类 我们可以把类分为两种 1 一种是java中已经定义好的类 如之前用过的Scanner类 Random类 这些我们直接拿过来用就可以了 2 另一种是需要我们自己去定义的类 我们可以在类中定义多个方法和属性来供我们实际的使用 什么是类
  • Android ViewGroup提高绘制性能

    如果下面有很多子View 绘制的时候 需要开启其子View的绘制缓存功能 从而提高绘制效率 public void setChildrenDrawingCacheEnabled boolean enabled final int count
  • 全国职业院校技能大赛云计算技术与应用大赛国赛题库答案(1)

    文章目录 IaaS 云计算基础架构平台 IaaS 云平台搭建 IaaS 云平台运维 IaaS 云计算基础架构平台 IaaS 云平台搭建 1 设置主机名 防火墙设置以及 SELinux 设置如下 1 设置控制节点主机名 controller
  • 产业AI公开课正式开播!60分钟解读AI对金融科技的全新破局

    京东数科 产业AI公开课 第一季第一期 重 磅 开 播 行业热门话题 实力业内大咖 深度解读 经典对话 绝对让你这1个小时的时间欲罢不能 干货满满 从SARS到这次新冠肺炎 黑天鹅 事件对资本市场造成极大影响 不同时期的应对之道有何不同 疫
  • 欧拉函数(数论)

    include
  • 团队的远程管理_远程团队指南:如何管理您的远程软件开发团队

    团队的远程管理 Guides to help you work remotely seem to have swept through the Internet these days 这些天来 帮助您远程工作的指南似乎席卷了Internet
  • GPIO相关知识点注解

    一 GPIO工作方式 1 1 GPIO输入 输入工作方式 输入路径 输入浮空模式 I O I O I O端口 gt
  • LabVIEW组态编程的五大经验总结,助你开发过程事半功倍

    虽然NI LabVIEW软件长期以来一直帮助工程师和科学家们快速开发功能测量和控制应用 但不是所有的新用户都会遵循LabVIEW编程的最佳方法 LabVIEW图形化编程比较独特 因为只需看一眼用户的应用程序 就马上可以发现用户是否遵循编码的
  • CVPR 2023|UniDetector:7000类通用目标检测算法(港大&清华)

    作者 CV君 编辑 极市平台 点击下方卡片 关注 自动驾驶之心 公众号 ADAS巨卷干货 即可获取 点击进入 自动驾驶之心 目标检测 技术交流群 导读 论文中仅用了500个类别参与训练 就可以使UniDetector检测超过7k个类别 向大
  • Visual Leak Detector - 增强内存泄漏检测工具 for Visual C++ (翻译)

    原文及源码下载地址 http www codeproject com KB applications visualleakdetector aspx 名词解释 1 stack trace 调用堆栈信息 2 debug heap 调试堆 3
  • [服务器][服务][教程]Windows Server 2022开启WebDAV享受媒体影音以及用户权限设置

    1 前言 传输协议那么多 为什么选择Webdav做媒体影音服务器 常用的共享协议有 Samba WebDAV NFS FTP SFTP 这里对这几个协议进行一下优劣对比 Samba 优点 支持的范围广 挂载方便 缺点 445端口被运营商封闭
  • Python环境—打包

    两个步骤完成python环境打包 1 打包 pip install conda pack conda activate py38 conda pack n py38 在当前路径生成py38 tar gz 2 移植 在另一台电脑 conda的
  • 大数据腾讯TEG面经——凉经

    一面 很多原理和计算机基础 c 1 反转链表和两个字符串最大公共子串 2 osi的七层和什么的四层 3 tcp和udp 三次握手 4 进程和线程区别 5 hadoop分布 zookeeper选举 6 hive和hbase区别 hbase都是
  • 基于 UML 的业务建模举例

    基于 UML 的业务建模 2011 05 30 作者 杨敏强 来源 网络 简介 对于管理流程咨询项目 大型信息化建设项目和套装管理软件实施项目 对业务环境的分析和理解对项目的成功至关重要 系统 全面理解 IT 系统所处的业务环境 可以帮助
  • FTP UPLOAD

    First you should add the following directives Listing 1 Directives using System Net using System IO The following steps