Created
June 21, 2014 09:45
-
-
Save imwower/4dad02f0479ed10e521c to your computer and use it in GitHub Desktop.
C# FTP Helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FileService : IFileService.IFileService | |
{ | |
private readonly string ftpUserName; | |
private readonly string ftpPassword; | |
private readonly string ftpRootPath; | |
public ILogger Logger { get; set; } | |
public FileService(string user, string password, string server) | |
{ | |
this.ftpUserName = user; | |
this.ftpPassword = password; | |
this.ftpRootPath = server.TrimEnd('/') + "/"; | |
} | |
public string UploadFile(string source) | |
{ | |
Logger.Debug("要上传的文件为: {0},FTP根目录为: {1}", source, ftpRootPath); | |
string fileName = GenerateFileName(source); | |
Logger.Debug("动态生成的文件名为: {0}", fileName); | |
var result = UploadFile(fileName, source); | |
Logger.Debug("上传成功!返回的文件路径为:{0}", fileName); | |
return fileName; | |
} | |
public byte[] DownloadFile(string source) | |
{ | |
Logger.Debug("读取FTP上的文件:{0}", source); | |
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpRootPath + source); | |
req.Credentials = new NetworkCredential(ftpUserName, ftpPassword); | |
req.Method = WebRequestMethods.Ftp.DownloadFile; | |
req.UseBinary = true; | |
try | |
{ | |
FtpWebResponse response = (FtpWebResponse)req.GetResponse(); | |
using (Stream ftpStream = response.GetResponseStream()) | |
using (var memoryStream = new MemoryStream()) | |
{ | |
ftpStream.CopyTo(memoryStream); | |
response.Close(); | |
req.Abort(); | |
return memoryStream.ToArray(); | |
} | |
} | |
catch (Exception e) | |
{ | |
Logger.Warn("读取文件时发生错误!{0}", e.Message); | |
req.Abort(); | |
return null; | |
} | |
} | |
public bool DeleteFile(string source) | |
{ | |
Logger.Debug("删除FTP上的文件:{0}", source); | |
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpRootPath + source); | |
req.Credentials = new NetworkCredential(ftpUserName, ftpPassword); | |
req.Method = WebRequestMethods.Ftp.DeleteFile; | |
try | |
{ | |
FtpWebResponse response = (FtpWebResponse)req.GetResponse(); | |
response.Close(); | |
} | |
catch (Exception e) | |
{ | |
Logger.Warn("删除文件时发生错误!{0}", e.Message); | |
req.Abort(); | |
return false; | |
} | |
req.Abort(); | |
Logger.Debug("删除成功!"); | |
return true; | |
} | |
#region private methods | |
/// <summary> | |
/// 上传文件到FTP指定目录 | |
/// </summary> | |
/// <param name="ftpFileName">FTP指定的目录,包含文件全名</param> | |
/// <param name="source"></param> | |
private bool UploadFile(string ftpFileName, string source) | |
{ | |
CreateFtpDirectory(ftpFileName); | |
FileInfo fi = new FileInfo(source); | |
FileStream fs = fi.OpenRead(); | |
long length = fs.Length; | |
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpRootPath + ftpFileName); | |
req.Credentials = new NetworkCredential(ftpUserName, ftpPassword); | |
req.Method = WebRequestMethods.Ftp.UploadFile; | |
req.ContentLength = length; | |
req.Timeout = 10 * 1000; | |
try | |
{ | |
Stream stream = req.GetRequestStream(); | |
int BufferLength = 4096; | |
byte[] b = new byte[BufferLength]; | |
int i; | |
while ((i = fs.Read(b, 0, BufferLength)) > 0) | |
{ | |
stream.Write(b, 0, i); | |
} | |
stream.Close(); | |
stream.Dispose(); | |
} | |
catch (Exception e) | |
{ | |
Logger.Error("上传文件时发生错误!", e); | |
return false; | |
} | |
finally | |
{ | |
fs.Close(); | |
req.Abort(); | |
} | |
req.Abort(); | |
return true; | |
} | |
/// <summary> | |
/// 根据当前时间生成文件路径和文件名。类似: | |
/// 2014/06/17/guid.png | |
/// </summary> | |
/// <param name="source">要上传文件的绝对路径</param> | |
/// <returns></returns> | |
private string GenerateFileName(string source) | |
{ | |
var extension = Path.GetExtension(source); | |
var now = DateTime.Now.ToString("yyyy/MM/dd"); | |
var guid = Guid.NewGuid().ToString(); | |
return now + "/" + guid + extension; | |
} | |
private void CreateFtpDirectory(string destFilePath) | |
{ | |
string fullDir = FtpParseDirectory(destFilePath); | |
string[] dirs = fullDir.Split('/'); | |
string curDir = "/"; | |
for (int i = 0; i < dirs.Length; i++) | |
{ | |
string dir = dirs[i]; | |
if (dir != null && dir.Length > 0) | |
{ | |
try | |
{ | |
curDir += dir + "/"; | |
if (!CheckIfDirectoryExists(curDir)) | |
MakeDirectory(curDir); | |
} | |
catch (Exception e) | |
{ | |
Logger.Error("创建FTP目录时出错!", e); | |
} | |
} | |
} | |
} | |
private static string FtpParseDirectory(string destFilePath) | |
{ | |
return destFilePath.Substring(0, destFilePath.LastIndexOf("/")); | |
} | |
/// <summary> | |
/// 检查FTP服务器上,指定的路径是否存在 | |
/// </summary> | |
/// <param name="localFile"></param> | |
/// <returns></returns> | |
private bool CheckIfDirectoryExists(string localFile) | |
{ | |
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpRootPath + localFile); | |
req.Credentials = new NetworkCredential(ftpUserName, ftpPassword); | |
req.Method = WebRequestMethods.Ftp.ListDirectory; | |
try | |
{ | |
FtpWebResponse response = (FtpWebResponse)req.GetResponse(); | |
response.Close(); | |
} | |
catch (Exception e) | |
{ | |
Logger.Warn("FTP目录 '{0}' 不存在!错误信息:{1}", localFile, e.Message); | |
req.Abort(); | |
return false; | |
} | |
Logger.Debug("存在FTP目录:{0}", localFile); | |
req.Abort(); | |
return true; | |
} | |
/// <summary> | |
/// 在FTP服务器上创建指定的目录 | |
/// </summary> | |
/// <param name="localFile"></param> | |
/// <returns></returns> | |
private bool MakeDirectory(string localFile) | |
{ | |
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpRootPath + localFile); | |
req.Credentials = new NetworkCredential(ftpUserName, ftpPassword); | |
req.Method = WebRequestMethods.Ftp.MakeDirectory; | |
try | |
{ | |
FtpWebResponse response = (FtpWebResponse)req.GetResponse(); | |
response.Close(); | |
} | |
catch (Exception e) | |
{ | |
Logger.Warn("创建FTP目录: '{0}'失败! 错误信息:{1}", localFile, e.Message); | |
req.Abort(); | |
return false; | |
} | |
Logger.Debug("创建FTP目录: '{0}'成功!", localFile); | |
req.Abort(); | |
return true; | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment