using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using UnityEngine; /// <summary>
/// 与 ftp 服务器通信的类
/// </summary>
public static class FtpHelper
{
const int MaxReconnectCount = ; // 最大的重新连接次数
static int s_reconnectCounter; static void ResetReconnectCounter()
{
s_reconnectCounter = ;
} static bool ReconnectCounterIncrease()
{
return ++s_reconnectCounter >= MaxReconnectCount;
} /// <summary>
/// 上传文件到 ftp 服务器
/// </summary>
/// <param name="srcFilePath">源文件路径</param>
/// <param name="targetUrl">目标 url</param>
/// <param name="credential">凭证</param>
public static void UploadFileToFTPServer(string srcFilePath, string targetUrl, NetworkCredential credential)
{
if (string.IsNullOrEmpty(srcFilePath))
throw new ArgumentException("srcFilePath");
if (string.IsNullOrEmpty(targetUrl))
throw new ArgumentException("targetUrl");
if (credential == null)
throw new ArgumentNullException("credential"); targetUrl = FixUrl(targetUrl, false); try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(targetUrl);
byte[] srcFileBuffer = File.ReadAllBytes(srcFilePath); request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = credential;
request.ContentLength = srcFileBuffer.Length;
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = false; using (Stream requestStream = request.GetRequestStream())
requestStream.Write(srcFileBuffer, , srcFileBuffer.Length); Debug.Log(string.Format("Upload file succeed, source file path: {0}, target url: {1}", srcFilePath, targetUrl)); ResetReconnectCounter();
}
catch (Exception ex)
{
string l = string.Format("Upload file failed, upload it again. source file path: {0}, target url: {1}, error message: {2}", srcFilePath, targetUrl, ex.Message);
Debug.LogError(l);
if (ReconnectCounterIncrease())
throw new WebException(l);
else
UploadFileToFTPServer(srcFilePath, targetUrl, credential);
}
} /// <summary>
/// 删除 ftp 服务器上的所有文件
/// </summary>
/// <param name="dirUrl">文件夹 url</param>
public static void DeleteAllFilesOnFtp(string dirUrl, NetworkCredential credential)
{
if (string.IsNullOrEmpty(dirUrl))
throw new ArgumentException("dirUrl");
if (credential == null)
throw new ArgumentNullException("credential"); dirUrl = FixUrl(dirUrl, true); List<string> dirNames, fileNames;
GetDirectoryList(dirUrl, credential, out dirNames, out fileNames); foreach (var dirName in dirNames)
{
string url = string.Format("{0}{1}/", dirUrl, dirName);
DeleteAllFilesOnFtp(url, credential);
} foreach (var fileName in fileNames)
{
string url = dirUrl + fileName;
DeleteFile(url, credential);
}
} /// <summary>
/// 获取 ftp 文件夹的列表
/// </summary>
public static void GetDirectoryList(string dirUrl, NetworkCredential credential, out List<string> dirNames, out List<string> fileNames)
{
if (string.IsNullOrEmpty(dirUrl))
throw new ArgumentException("dirUrl");
if (credential == null)
throw new ArgumentNullException("credential"); dirUrl = FixUrl(dirUrl, true); dirNames = new List<string>();
fileNames = new List<string>(); try
{
var request = (FtpWebRequest)WebRequest.Create(dirUrl); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = credential;
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = false; var response = (FtpWebResponse)request.GetResponse();
var responseStream = response.GetResponseStream();
var responseReader = new StreamReader(responseStream); while (!responseReader.EndOfStream)
{
string line = responseReader.ReadLine();
if (string.IsNullOrEmpty(line))
continue; string[] words = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string name = words.Last(); if (line[] == 'd') // 表示是文件夹
dirNames.Add(name);
else if (line[] == '-') // 表示是文件
fileNames.Add(name);
} responseReader.Dispose();
response.Close();
responseStream.Dispose();
}
catch (Exception ex)
{
string l = string.Format("Get directory list failed, directory url: {0}, error message: {1}", dirUrl, ex.Message);
Debug.LogError(l);
throw new WebException(l);
}
} /// <summary>
/// 删除 ftp 服务器上的文件
/// </summary>
public static void DeleteFile(string fileUrl, NetworkCredential credential)
{
if (string.IsNullOrEmpty(fileUrl))
throw new ArgumentException("fileUrl");
if (credential == null)
throw new ArgumentNullException("credential"); fileUrl = FixUrl(fileUrl, false); try
{
var request = (FtpWebRequest)WebRequest.Create(fileUrl); request.Method = WebRequestMethods.Ftp.DeleteFile;
request.Credentials = credential;
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = false; var response = request.GetResponse();
response.Close(); Debug.Log(string.Format("Delete file succeed, url: {0}", fileUrl)); ResetReconnectCounter();
}
catch (Exception ex)
{
string l = string.Format("Delete file failed, url: {0}, error message: {1}", fileUrl, ex.Message);
Debug.LogError(l);
if (ReconnectCounterIncrease())
throw new WebException(l);
else
DeleteFile(fileUrl, credential);
}
} /// <summary>
/// 在 ftp 服务器上创建文件夹
/// </summary>
/// <param name="dirUrl"></param>
/// <param name="credential"></param>
public static void CreateFolder(string dirUrl, NetworkCredential credential)
{
if (string.IsNullOrEmpty(dirUrl))
throw new ArgumentException("dirUrl");
if (credential == null)
throw new ArgumentNullException("credential"); dirUrl = FixUrl(dirUrl, false); string folderName = Path.GetFileNameWithoutExtension(dirUrl);
string parentFolderUrl = dirUrl.Replace(folderName, "");
List<string> dirNames, fileNames; GetDirectoryList(parentFolderUrl, credential, out dirNames, out fileNames); if (dirNames.Contains(folderName))
return; try
{
var request = (FtpWebRequest)WebRequest.Create(dirUrl); request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = credential;
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = false; var response = request.GetResponse();
response.Close(); Debug.Log(string.Format("Create folder succeed, url: {0}", dirUrl)); ResetReconnectCounter();
}
catch (Exception ex)
{
string l = string.Format("Create folder failed, create again, url: {0}, error message: {1}", dirUrl, ex.Message);
Debug.LogError(l);
if (ReconnectCounterIncrease())
throw new WebException(l);
else
CreateFolder(dirUrl, credential);
}
} static string FixUrl(string url, bool endWithSprit)
{
if (string.IsNullOrEmpty(url))
{
return url;
} url = url.Replace("\\", "/").TrimEnd('/');
return endWithSprit ? url + "/" : url;
}
}

参考1

转载请注明出处:http://www.cnblogs.com/jietian331/p/4955220.html

 using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text; namespace FtpUploader
{
class FtpManager
{
NetworkCredential m_credential;
string m_rootUri;
bool m_usePassive;
List<string> m_directories = new List<string>();
List<string> m_files = new List<string>(); static string FixUrl(string old)
{
return !string.IsNullOrEmpty(old) ?
old.Replace("\\", "/").TrimEnd('/') :
"";
} static string FixRelativePath(string old)
{
return !string.IsNullOrEmpty(old) ?
old.Replace("\\", "/").TrimEnd('/').TrimStart('/') :
"";
} public FtpManager(string userName, string password, string rootUri, bool usePassive)
{
if (string.IsNullOrEmpty(rootUri))
throw new ArgumentException("rootUri"); m_credential = new NetworkCredential(userName, password);
m_rootUri = FixUrl(rootUri);
m_usePassive = usePassive;
GetInfoRecursive("");
} FtpWebRequest CreateRequest(string uri, string method)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
request.Method = method;
request.Credentials = m_credential;
request.UsePassive = m_usePassive;
request.UseBinary = true;
request.KeepAlive = true;
return request;
} void GetInfoRecursive(string relativePath)
{
string fullUri = CombineUri(relativePath);
FtpWebRequest request = CreateRequest(fullUri, WebRequestMethods.Ftp.ListDirectoryDetails);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream); List<string> dirs = new List<string>();
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
string[] words = line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
string name = words.Last();
if (name != "." && name != "..")
{
char type = line[];
string newPath = !string.IsNullOrEmpty(relativePath) ? string.Format("{0}/{1}", relativePath, name) : name;
newPath = FixRelativePath(newPath); if (type == 'd')
{
m_directories.Add(newPath);
dirs.Add(newPath);
}
else if (type == '-')
{
m_files.Add(newPath);
}
}
} response.Dispose();
stream.Dispose();
reader.Dispose(); foreach (var dir in dirs)
{
GetInfoRecursive(dir);
}
} string CombineUri(params string[] relativePaths)
{
string uri = m_rootUri;
foreach (var p in relativePaths)
{
if (!string.IsNullOrEmpty(p))
uri = string.Format("{0}/{1}", uri, FixRelativePath(p));
}
return uri;
} /// <summary>
/// 将若干个文件传到 ftp 服务器
/// </summary>
/// <param name="files">若干文件的路径</param>
/// <param name="ftpFolders">若干文件对应在ftp服务器上的存放文件夹路径</param>
public void Upload(string[] files, string[] ftpFolders)
{
if (files == null || ftpFolders == null)
throw new ArgumentNullException("files == null || ftpFolders == null");
if (files.Length != ftpFolders.Length)
throw new ArgumentException("files.Length != ftpFolders.Length");
if (files.Length < )
return; // 先创建好文件夹
List<string> targetFolders = new List<string>();
foreach (var folder in ftpFolders)
{
string fixedPath = FixRelativePath(folder);
string[] words = fixedPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); for (int i = ; i < words.Length; i++)
{
string path = words[];
for (int j = ; j <= i; j++)
path = string.Format("{0}/{1}", path, words[j]); if (!targetFolders.Contains(path))
targetFolders.Add(path);
}
} foreach (var f in targetFolders)
{
CreateFolder(f);
} // 上传
for (int i = ; i < files.Length; i++)
UploadFile(files[i], ftpFolders[i]); Console.WriteLine("All files are uploaded succeed!");
} /// <summary>
/// 将整个文件夹的内容传到ftp服务器,目录结构保持不变
/// </summary>
/// <param name="folder">源文件夹路径</param>
/// <param name="ftpFolder">ftp服务器上对应的文件夹路径</param>
public void Upload(string folder, string ftpFolder)
{
if (string.IsNullOrEmpty(folder))
throw new ArgumentException("folder"); folder = FixUrl(folder);
ftpFolder = FixRelativePath(ftpFolder); string[] files = Directory.GetFiles(folder, "*.*", SearchOption.AllDirectories);
string[] folders = new string[files.Length]; for (int i = ; i < files.Length; i++)
{
string file = FixUrl(files[i]);
string name = Path.GetFileName(file);
string relativeFolder = file.Substring(folder.Length, file.Length - folder.Length - name.Length);
folders[i] = string.Format("{0}/{1}", ftpFolder, FixRelativePath(relativeFolder));
} // 上传
Upload(files, folders);
} void UploadFile(string srcPath, string relativeFolder)
{
string name = Path.GetFileName(srcPath);
string uri = CombineUri(relativeFolder, name);
byte[] srcFileBuffer = File.ReadAllBytes(srcPath); FtpWebRequest request = CreateRequest(uri, WebRequestMethods.Ftp.UploadFile);
request.ContentLength = srcFileBuffer.Length; using (Stream requestStream = request.GetRequestStream())
requestStream.Write(srcFileBuffer, , srcFileBuffer.Length); m_files.Add(string.Format("{0}/{1}", FixRelativePath(relativeFolder), name)); Console.WriteLine("Upload file succeed! {0} -> {1}", srcPath, uri);
} public void UploadString(string src, string relativePath)
{
if (string.IsNullOrEmpty(src))
throw new ArgumentException("src"); string uri = CombineUri(relativePath);
byte[] buffer = Encoding.Default.GetBytes(src); FtpWebRequest request = CreateRequest(uri, WebRequestMethods.Ftp.UploadFile);
request.ContentLength = buffer.Length; using (Stream requestStream = request.GetRequestStream())
requestStream.Write(buffer, , buffer.Length); m_files.Add(FixRelativePath(relativePath));
} void CreateFolder(string relativePath)
{
relativePath = FixRelativePath(relativePath);
if (string.IsNullOrEmpty(relativePath))
throw new ArgumentException("relativePath"); if (m_directories.Contains(relativePath))
return; string fullUri = CombineUri(relativePath);
FtpWebRequest request = CreateRequest(fullUri, WebRequestMethods.Ftp.MakeDirectory);
WebResponse response = request.GetResponse();
response.Dispose(); m_directories.Add(relativePath); Console.WriteLine("Create folder succeed! {0}", fullUri);
} public string DownloadFile(string relativePath)
{
relativePath = FixRelativePath(relativePath);
if (string.IsNullOrEmpty(relativePath))
return null; if (!m_files.Contains(relativePath))
return null; string fullUri = CombineUri(relativePath);
FtpWebRequest request = CreateRequest(fullUri, WebRequestMethods.Ftp.DownloadFile);
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream); string text = sr.ReadToEnd(); response.Dispose();
stream.Dispose();
sr.Dispose(); return text;
} public List<string> Directoreis
{
get { return m_directories; }
} public List<string> Files
{
get { return m_files; }
}
}
}

参考2

using System;

namespace FtpUploader
{
class Program
{
static void Main(string[] args)
{
#if true
if (args == null || args.Length < )
throw new ArgumentException("args == null || args.Length < 1"); Console.WriteLine("Start uploading, args is: {0}", args[]);
string[] lines = args[].Split(',');
#else
string a = @"ftp://120.92.34.206,uniuftp,ryx387b1,False,True,D:/SVN/art/UnityArt/AssetBundles/PC/Products,AssetBundle/PC";
string[] lines = a.Split(',');
#endif
string uri = lines[];
string userName = lines[];
string password = lines[];
bool usePassive;
bool.TryParse(lines[], out usePassive); // 上传
FtpManager ftp = new FtpManager(userName, password, uri, usePassive); bool folderStyle;
bool.TryParse(lines[], out folderStyle);
if (folderStyle)
{
string folder = lines[];
string relativeFolder = lines[];
ftp.Upload(folder, relativeFolder); // 整合版本文件
CreateAndUploadVersionFile(ftp, relativeFolder);
}
else
{
string[] files = lines[].Split(new char['|'], StringSplitOptions.RemoveEmptyEntries);
string[] folders = lines[].Split(new char['|'], StringSplitOptions.RemoveEmptyEntries);
ftp.Upload(files, folders);
} Console.WriteLine("按任意健结束...");
Console.ReadKey();
} static void CreateAndUploadVersionFile(FtpManager ftp, string relativeFolder)
{
relativeFolder = relativeFolder.Replace("\\", "/").TrimEnd('/');
string mainVersionString = ftp.DownloadFile(relativeFolder + "/mainVersion.dat");
string musicVersionString = ftp.DownloadFile(relativeFolder + "/musicVersion.dat");
string artVersionString = ftp.DownloadFile(relativeFolder + "/artVersion.dat"); int mainVersion = , musicVersion = , artVersion = ;
int.TryParse(mainVersionString, out mainVersion);
int.TryParse(musicVersionString, out musicVersion);
int.TryParse(artVersionString, out artVersion);
string versionString = string.Format("{0}.{1}.{2}\nmainList.dat,musicList.dat,artList.dat", mainVersion, musicVersion, artVersion); ftp.UploadString(versionString, relativeFolder + "/version.dat"); Console.WriteLine("整合版本文件成功!版本号为: {0}", versionString);
}
}
}

c#之向ftp服务器传文件的更多相关文章

  1. swift之向ftp服务器传文件

    在 mac 上如何使用 xcode, swift 语言开发一个向 ftp 服务器上传文件的工具? 使用的是第三方库 Rebekka,下载地址为:https://github.com/Constanti ...

  2. FTP上传文件到服务器

    一.初始化上传控件. 1.我们这里用dropzone.js作为上传控件,下载地址http://www.dropzonejs.com/ 2.这里我们使用一个div元素作为dropzone载体. < ...

  3. C# FTP上传文件至服务器代码

    C# FTP上传文件至服务器代码 /// <summary> /// 上传文件 /// </summary> /// <param name="fileinfo ...

  4. C# FTP上传文件时出现"应 PASV 命令的请求,服务器返回了一个与 FTP 连接地址不同的地址。"的错误

    FTP上传文件时出现"应 PASV 命令的请求,服务器返回了一个与 FTP 连接地址不同的地址."的错误 解决方法是在原代码上增加这句话 reqFTP.UsePassive = f ...

  5. PHP使用FTP上传文件到服务器(实战篇)

    我们在做开发的过程中,上传文件肯定是避免不了的,平常我们的程序和上传的文件都在一个服务器上,我们也可以使用第三方sdk上传文件,但是文件在第三方服务器上.现在我们使用PHP的ftp功能把文件上传到我们 ...

  6. 再看ftp上传文件

    前言 去年在项目中用到ftp上传文件,用FtpWebRequest和FtpWebResponse封装一个帮助类,这个在网上能找到很多,前台使用Uploadify控件,然后在服务器上搭建Ftp服务器,在 ...

  7. FTP上传文件提示550错误原因分析。

    今天测试FTP上传文件功能,同样的代码从自己的Demo移到正式的代码中,不能实现功能,并报 Stream rs = ftp.GetRequestStream()提示远程服务器返回错误: (550) 文 ...

  8. FTP 上传文件

    有时候需要通过FTP同步数据文件,除了比较稳定的IDE之外,我们程序员还可以根据实际的业务需求来开发具体的工具,具体的开发过程就不细说了,这里了解一下通过C#实现FTP上传文件到指定的地址. /// ...

  9. Java ftp 上传文件和下载文件

    今天同事问我一个ftp 上传文件和下载文件功能应该怎么做,当时有点懵逼,毕竟我也是第一次,然后装了个逼,在网上找了一段代码发给同事,叫他调试一下.结果悲剧了,运行不通过.(装逼失败) 我找的文章链接: ...

随机推荐

  1. Zabbix3.0 客户端搭建

    zabbix客户端安装 我们这边使用编译安装 软件包版本 zabbix-3.0.3.tar.gz 添加用户组 #groupadd zabbix #useradd -s /sbin/nologin -g ...

  2. boost ASIO实例

    client端代码 #include <iostream> #include <boost/asio.hpp> #include <boost/bind.hpp> ...

  3. java 单例模式及getInstance的好处

    1.什么是单例模式 简单理解为,有一个类,只能有一个实例化对象,这就是单例模式. 2.getInstance的好处 首先看一下怎样使用getInstance实现单例模式 public class Co ...

  4. EL表达式处理字符串 是否 包含 某字符串 截取 拆分...............

    EL表达式处理字符串 是否 包含 某字符串 截取 拆分............... JSP页面页头添加<%@ taglib uri="/WEB-INF/taglib/c.tld&qu ...

  5. CSS中如何把Span标签设置为固定宽度

    一.形如<span>ABC</span>独立行设置SPAN为固定宽度方法如下: span {width:60px; text-align:center; display:blo ...

  6. Jquery 控制元素 上 下 移动

    <html> <head> <meta http-equiv="Content-Type" content="text/html; char ...

  7. 火狐解决OCSP回应包含过期信息的问题

    连接 addons.mozilla.org 时发生错误. OCSP 回应包含过期信息. (错误码: sec_error_ocsp_old_response)hosts文件添加 vi /etc/host ...

  8. frame、bounds表示大小和位置的属性以及center、position、anchorPosition

    在iOS开发开发过程中经常会用到界面元素的frame.bounds表示大小和位置的属性以及center.position.anchorPosition等单纯表示位置的属性.这些属性究竟什么含义?彼此间 ...

  9. Linux一些命令

    1.查看系统安装软件 rpm -qa  //(不包括绿色安装的软件程序,也就是直接在安装目录中启动的不包括) rpm -qa |grep gcc 参数解释:q ——询问 a —— 查询全部   l — ...

  10. linux下的vim使用笔记

    环境:window下可以使用gvim编辑软件 学习主要是在ubuntu15敲击命令学习的视频来自于智普教育vim使用视频1. sudo apt show vi 查看安装的vi版本,当然了我的ubunt ...