c#之向ftp服务器传文件
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服务器传文件的更多相关文章
- swift之向ftp服务器传文件
在 mac 上如何使用 xcode, swift 语言开发一个向 ftp 服务器上传文件的工具? 使用的是第三方库 Rebekka,下载地址为:https://github.com/Constanti ...
- FTP上传文件到服务器
一.初始化上传控件. 1.我们这里用dropzone.js作为上传控件,下载地址http://www.dropzonejs.com/ 2.这里我们使用一个div元素作为dropzone载体. < ...
- C# FTP上传文件至服务器代码
C# FTP上传文件至服务器代码 /// <summary> /// 上传文件 /// </summary> /// <param name="fileinfo ...
- C# FTP上传文件时出现"应 PASV 命令的请求,服务器返回了一个与 FTP 连接地址不同的地址。"的错误
FTP上传文件时出现"应 PASV 命令的请求,服务器返回了一个与 FTP 连接地址不同的地址."的错误 解决方法是在原代码上增加这句话 reqFTP.UsePassive = f ...
- PHP使用FTP上传文件到服务器(实战篇)
我们在做开发的过程中,上传文件肯定是避免不了的,平常我们的程序和上传的文件都在一个服务器上,我们也可以使用第三方sdk上传文件,但是文件在第三方服务器上.现在我们使用PHP的ftp功能把文件上传到我们 ...
- 再看ftp上传文件
前言 去年在项目中用到ftp上传文件,用FtpWebRequest和FtpWebResponse封装一个帮助类,这个在网上能找到很多,前台使用Uploadify控件,然后在服务器上搭建Ftp服务器,在 ...
- FTP上传文件提示550错误原因分析。
今天测试FTP上传文件功能,同样的代码从自己的Demo移到正式的代码中,不能实现功能,并报 Stream rs = ftp.GetRequestStream()提示远程服务器返回错误: (550) 文 ...
- FTP 上传文件
有时候需要通过FTP同步数据文件,除了比较稳定的IDE之外,我们程序员还可以根据实际的业务需求来开发具体的工具,具体的开发过程就不细说了,这里了解一下通过C#实现FTP上传文件到指定的地址. /// ...
- Java ftp 上传文件和下载文件
今天同事问我一个ftp 上传文件和下载文件功能应该怎么做,当时有点懵逼,毕竟我也是第一次,然后装了个逼,在网上找了一段代码发给同事,叫他调试一下.结果悲剧了,运行不通过.(装逼失败) 我找的文章链接: ...
随机推荐
- nm applet disable
http://support.qacafe.com/knowledge-base/how-do-i-prevent-network-manager-from-controlling-an-interf ...
- 8.3 sikuli 集成进eclipse 报错:eclipse中运行提示 Win32Util.dll: Can't load 32-bit .dll on a AMD 64 bit platform
sikuli运行出现问题:Win32Util.dll: Can't load 32-bit .dll on a AMD 64 bit platform 在64位平台上无法加载32位的dll文件 解决办 ...
- iframe子页面调用父页面javascript函数的方法
1.iframe子页面调用 父页面js函数 子页面调用父页面函数只需要写上window.parent就可以了.比如调用a()函数,就写成: window.parent.a(); 2.iframe父页面 ...
- ligerUI调用$.ligerDialog.open弹出窗口,关闭后无法获取焦点问题
1:调用父窗口某一个文件框,获取焦点, parent.window.document.getElementByIdx_x("roleName").focus(); 2:关闭父窗 ...
- lucene 中关于Store.YES 关于Store.NO的解释
总算搞明白 lucene 中关于Store.YES 关于Store.NO的解释了 一直对Lucene Store.YES不太理解,网上多数的说法是存储字段,NO为不存储. 这样的解释有点郁闷:字面意 ...
- java 线程安全
要认识java线程安全,必须了解两个主要的点:java的内存模型,java的线程同步机制.特别是内存模型,java的线程同步机制很大程度上都是基于内存模型而设定的. 浅谈java内存模型: 不同的平台 ...
- JSP标准标签库(JSTL)--XML标签库 x
³在开发中XML解析的操作是非常烦琐的,幸运的是在JSTL中专门提供了用于XML解析的操作,这样用户就可以不用费力的去研究SAX或DOM等操作的使用,就可以轻松的进行XML文件的解析处理. XML标 ...
- JSP文件上传--FileUpload组件
如果使用上传操作,并且没有使用框架之类,最好使用Smartupload,因为FileUpdate太难使用. 下载组件: fileupload包:http://commons.apache.org/pr ...
- 8、代理模式(Proxy)
其实每个模式名称就表明了该模式的作用,代理模式就是多一个代理类出来,替原对象进行一些操作,比如我们在租房子的时候回去找中介,为什么呢?因为你对该地区房屋的信息掌握的不够全面,希望找一个更熟悉的人去帮你 ...
- 用Eclipse 统计代码行数小技巧
今天公司SQA问我目前项目代码行数有多少,我当时就是想,以前好像写过类似的统计工具但是一时又找不到 公司网络又不能下载,所以想想eclipse是不是又类似功能,找了下没有,但突然一想有一个转弯方法:统 ...