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. keepalived 健康检测

    1.TCP方式 详见:http://www.cnblogs.com/tengpan-cn/p/5776574.html 以下内容,都是基于此进行修改 2.HTTP_GET 根据返回状态判断服务器是否正 ...

  2. 转 [分享一个SQL] 查会话阻塞关系,层次关系.

    with ash as (select /*+ materialize*/* from DBA_HIST_ACTIVE_SESS_HISTORY  where sample_time between ...

  3. C++中的基本数据类型

    C++中定义了一组表示整数.浮点数.单个字符和布尔值的算术类型(arithmetic type). 另外还定义了一种叫做void的特殊类型.void类型没有对应的值,仅用在有限的一些情况下,通常用作无 ...

  4. Dense Subsequence

    Dense Subsequence time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...

  5. shell注意事项

    以下基于bash 1.shell只有变量和数组?,数组() 2.( (表达式1,表达式2…) ) 3.[ expr ] 实际上是bash 中 test 命令的简写.即所有的 [ expr ] 等于 t ...

  6. HDU/5499/模拟

    题目链接 模拟题,直接看代码. £:分数的计算方法,要用double; #include <set> #include <map> #include <cmath> ...

  7. %3f URL --> '?'拼接引发的问题

    转载自:https://www.reddit.com/r/swift/comments/2w19kp/how_do_you_send_a_through_nsmutableurlrequest/ ho ...

  8. android 中ImageButton按下改变背景图片的效果

    最近在做一个app的登陆界面,才发现原来认为很简单的UI效果,其实背后却蕴含的知识很多,积累一个算一个吧. 实现方法有两种:一种是添加代码,一种是配置xml文件. 方法一:代码添加 ImageButt ...

  9. Android中布局文件中使用onClick属性

    安卓开发中,布局文件中的控件有一个属性,是onClick,例如:           <Button             android:id="@+id/button1" ...

  10. startActivityForResult与onActivityResult

    androidActivity之间的跳转不只是有startActivity(Intent i)的,startActivityForResult(Intent intent, int requestCo ...