您的位置:首页 > 编程语言 > C#

c#之向ftp服务器传文件

2015-11-11 09:35 501 查看
.Net提供了FtpWebRequest类,代码如下:

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 = 3;        // 最大的重新连接次数
static int s_reconnectCounter;

static void ResetReconnectCounter()
{
s_reconnectCounter = 0;
}

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, 0, 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[0] == 'd')         // 表示是文件夹
dirNames.Add(name);
else if (line[0] == '-')    // 表示是文件
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;
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: