using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace FTP24CP
{
public class FtpHelper
{
public static string ftpServerIP = "";
public static string ftpUserID = "";
public static string ftpPassword = "";
public static string saveServerDomin = "";
/// <summary>
/// 上传文件,创建文件夹
/// </summary>
/// <param name="localFile"></param>
/// <returns>文件路径</returns>
public static string FtpUpload(string localFile)
{
DateTime dt = DateTime.Now;
string ftpPath = "/filepath/" + dt.Year.ToString() + "/" + dt.Month.ToString() + "/" + dt.Day + "/";
//检查目录是否存在,不存在创建
FtpCheckDirectoryExist(ftpPath);
FileInfo fi = new FileInfo(localFile);
FileStream fs = fi.OpenRead();
long length = fs.Length;
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpServerIP + ftpPath + fi.Name);
req.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
req.Method = WebRequestMethods.Ftp.UploadFile;
req.ContentLength = length;
req.Timeout = 10 * 1000;
try
{
Stream stream = req.GetRequestStream();
int BufferLength = 2048; //2K
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)
{
string ss = e.Message + e.StackTrace;
return "";
}
finally
{
fs.Close();
req.Abort();
}
req.Abort();
string newPath = saveServerDomin + ftpPath + fi.Name;
return newPath;
}
/// <summary>
/// 上传文件
/// </summary>
/// <param name="localFile"></param>
/// <returns></returns>
public static bool UploadNotCreateFile(string localFile)
{
FileInfo fileInf = new FileInfo(localFile);
string uri = "" + ftpServerIP + "/" + fileInf.Name;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("" + ftpServerIP + "/" + fileInf.Name));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
//判断文件的目录是否存,不存则创建
public static void FtpCheckDirectoryExist(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 + "/";
FtpMakeDir(curDir);
}
catch (Exception)
{ }
}
}
}
public static string FtpParseDirectory(string destFilePath)
{
return destFilePath.Substring(0, destFilePath.LastIndexOf("/"));
}
//创建目录
public static bool FtpMakeDir(string localFile)
{
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(ftpServerIP + localFile);
req.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
req.Method = WebRequestMethods.Ftp.MakeDirectory;
try
{
FtpWebResponse response = (FtpWebResponse)req.GetResponse();
response.Close();
}
catch (Exception)
{
req.Abort();
return false;
}
req.Abort();
return true;
}
/// <summary>
///删除文件
/// </summary>
/// <param name="fileName"></param>
public static bool DeleteFTP(string fileName)
{
try
{
string uri = "" + ftpServerIP + "/" + fileName;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("" + ftpServerIP + "/" + fileName));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
string result = String.Empty;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// ftp下载文件
/// </summary>
/// <param name="filePath"></param>
/// <param name="fileName"></param>
/// <returns></returns>
public static bool Download(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("" + ftpServerIP + "/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
return true;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// 获取文件详情列表
/// </summary>
/// <returns></returns>
private string[] GetFilesDetailList()
{
string[] downloadFiles;
try
{
StringBuilder result = new StringBuilder();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("" + ftpServerIP + "/"));
ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf("\n"), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
downloadFiles = null;
return downloadFiles;
}
}
/// <summary>
/// 获取文件列表
/// </summary>
/// <returns></returns>
public string[] GetFileList()
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("" + ftpServerIP + "/"));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
downloadFiles = null;
return downloadFiles;
}
}
}
}
FTP文件上传(自定义文件夹)、删除、下载、读取
最新推荐文章于 2024-06-17 13:59:35 发布