C#FTP文件上传操作

public class FTP

{

static FtpWebRequest reqFTP;

static WebResponse response;

static StreamReader ftpStream;

static Stream strm;

static FileStream fs;

//const string temp = "temp";

static string filenametemp = "";

static string ftpServerIP = ConfigurationManager.AppSettings["ftpIP"];

static string ftpUserID = ConfigurationManager.AppSettings["ftpUid"];

static string ftpPassword = ConfigurationManager.AppSettings["ftpPwd"];

/// <summary>

/// 上传

/// </summary>

/// <param name="path">绝对路径</param>

/// <param name="filename">经销商文件夹名称</param>

/// <returns></returns>

public static bool Upload(string path,string filename)

{

bool bol = false;

string ftppath= @"ftp://" + ftpServerIP;

//fileRename(ftppath, "Test1", temp);

if (CheckFTPFile(filename, ftppath))

{

if (StatusUpLoad("", filename, path, ftppath))

{

bol = true;

}

}

else

{

if (CreateFile(ftppath + "/" + filename))

{

if (!CheckFTPFile("Advert", ftppath + "/" + filename))

{

CreateFile(ftppath + "/" + filename + "/Advert");//创建广告文件夹

}

if (!CheckFTPFile("Attachments", ftppath + "/" + filename))

{

CreateFile(ftppath + "/" + filename + "/Attachments");//创建附件文件夹

}

if (StatusUpLoad("", filename, path, ftppath))

{

bol = true;

}

}

}

return bol;

}

/// <summary>

/// 上传到ftp

/// </summary>

/// <param name="filename"></param>

/// <param name="filename"></param>

/// <param name="path"></param>

/// <param name="ftppath"></param>

/// <param name="ftpUserID"></param>

/// <param name="ftpPassword"></param>

/// <returns></returns>

private static bool StatusUpLoad(string AdorAt,string filename,string path, string ftppath)

{

bool bol = false;

string url = "";

string _newpath = "";

FileInfo fileInf = new FileInfo(path);

if (AdorAt == "Advert" && AdorAt == "Attachments")

{

url = ftppath + "/" + filename + "/" + AdorAt + "/" + fileInf.Name;

}

else

{

_newpath = CheckFTPFileChildren(ftppath + "/" + filename);

if (_newpath != "")

{

url = _newpath + "/" + fileInf.Name;

}

else

{

new Exception();

}

}

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));

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;

fs = fileInf.OpenRead();

try

{

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();

bol = true;

}

catch (Exception ex)

{

bol = false;

}

return bol;

}

/// <summary>

/// 判断一级文件夹是否存在

/// </summary>

/// <param name="fileName">要判断的文件名</param>

/// <param name="strFTPPath">ftp路径</param>

/// <param name="ftpUserID"></param>

/// <param name="ftpPassword"></param>

/// <returns></returns>

public static bool CheckFTPFile(string fileName, string strFTPPath)

{

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFTPPath));

reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

reqFTP.UseBinary = true;

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

response = (FtpWebResponse)reqFTP.GetResponse();

ftpStream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);

List<string> files = new List<string>();

string line = ftpStream.ReadLine();

while (line != null)

{

if (line.Contains("<DIR>"))

{

files.Add(line);

}

line = ftpStream.ReadLine();

}

response.Close();

ftpStream.Close();

bool fag = false;

for (int i = 0; i < files.Count; i++)

{

string[] strfiles = files[i].Split(‘ ‘);

string file = strfiles[strfiles.Length - 1];

if (file == fileName)

{

fag = true;

break;

}

}

return fag;

}

/// <summary>

/// 判断文件是否存在

/// </summary>

/// <param name="fileName">文件</param>

/// <param name="strFTPPath">路径</param>

/// <param name="ftpUserID"></param>

/// <param name="ftpPassword"></param>

/// <returns></returns>

public static string CheckFTPFileChildren(string strFTPPath)

{

int number;

string urlpath = "";

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFTPPath));

reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

reqFTP.UseBinary = true;

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

try

{

response = (FtpWebResponse)reqFTP.GetResponse();

ftpStream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);

List<string> files = new List<string>();

string line = ftpStream.ReadLine();

while (line != null)

{

if (line.Contains("<DIR>"))

{

files.Add(line);

}

line = ftpStream.ReadLine();

}

response.Close();

ftpStream.Close();

bool fag = false;

int count = files.Count;

for (int i = 0; i < files.Count; i++)

{

string[] strfiles = files[i].Split(‘ ‘);

string file = strfiles[strfiles.Length - 1];

if (file != "Advert" && file != "Attachments")

{

number = CheckFileNumber(strFTPPath + "/" + file);

if (number < 20)

{

urlpath = strFTPPath + "/" + file;

fag = true;

break;

}

}

}

if (!fag)

{

while (true)

{

urlpath = strFTPPath + "/" + (count - 1);

if (CreateFile(urlpath))

{

filenametemp = (count - 1).ToString();

break;

}

count++;

}

}

}

catch

{

urlpath = "";

}

return urlpath;

}

/// <summary>

/// 判断数量

/// </summary>

/// <param name="strFTPPath"></param>

/// <param name="ftpUserID"></param>

/// <param name="ftpPassword"></param>

/// <returns></returns>

public static int CheckFileNumber(string strFTPPath)

{

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFTPPath));

reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

reqFTP.UseBinary = true;

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

response = (FtpWebResponse)reqFTP.GetResponse();

ftpStream = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);

List<string> files = new List<string>();

string line = ftpStream.ReadLine();

while (line != null)

{

if (!line.Contains("<DIR>"))

{

files.Add(line);

}

line = ftpStream.ReadLine();

}

response.Close();

ftpStream.Close();

return files.Count;

}

/// <summary>

/// 创建文件夹

/// </summary>

/// <param name="dirName"></param>

public static bool CreateFile(string strFTPPath)

{

try

{

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(strFTPPath));

reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;

reqFTP.UseBinary = true;

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

response = (FtpWebResponse)reqFTP.GetResponse();

strm = response.GetResponseStream();

strm.Close();

response.Close();

return true;

}

catch (Exception ex)

{

return false;

}

}

/// <summary>

/// 删除文件

/// </summary> ftppath=ftppath+"//Test\\6ec5069d-7f17-4ce4-852b-0e1d996aca2f.jpg";

/// <param name="fileName"></param>

public static bool DeleteFile(string path)

{

try

{

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpUserID);

reqFTP.KeepAlive = false;

reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

string result = String.Empty;

response = (FtpWebResponse)reqFTP.GetResponse();

long size = response.ContentLength;

strm = response.GetResponseStream();

ftpStream = new StreamReader(strm);

result = ftpStream.ReadToEnd();

strm.Close();

ftpStream.Close();

response.Close();

return true;

}

catch (Exception ex)

{

return false;

}

}

public static void fileRename(string ftpPath, string oldFileName, string newFileName)

{

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpPath + "/" + oldFileName));

reqFTP.Method = WebRequestMethods.Ftp.Rename;

reqFTP.UseBinary = true;

reqFTP.RenameTo = newFileName;

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

response = (FtpWebResponse)reqFTP.GetResponse();

strm = response.GetResponseStream();

response.Close();

strm.Close();

}

}

时间: 2024-10-08 10:32:49

C#FTP文件上传操作的相关文章

FTP文件上传与下载

实现FTP文件上传与下载可以通过以下两种种方式实现,分别为:1.通过JDK自带的API实现:2.通过Apache提供的API是实现. 第一种方式 [java] view plaincopy package com.cloudpower.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import sun.n

Java实现FTP文件上传与下载

实现FTP文件上传与下载可以通过以下两种种方式实现(不知道还有没有其他方式),分别为:1.通过JDK自带的API实现:2.通过Apache提供的API是实现. 第一种方式 package com.cloudpower.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import sun.net.Telnet

FTP文件上传下载及验证

FTP文件上传下载及验证 有时候经常用到FTP的上传下载,本身代码相对比较简单,但有时需要考虑到文件上传下载进行验证.大体思路是上传时将FTP日志重定向到本地文件,再根据FTP返回码进行检查,这样有个缺点就是不能检验文件上传的完整性:下载时利用ls,ll命令查看是否存在. 上传代码 uploadFile() { ftp -i -v -n <<! >/tmp/ftp.log open $FTP_IP $FTP_PORT user $USER_ID $PASSWORD prompt cd $

Quartz石英调度实现ftp文件上传

Quartz石英调度实现ftp文件上传 实现一个每月1号00点01分自动生成的文件,通过ftp传到另一台主机上 1.先创建一个job任务类FtpUploadFileJobTask import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.apache.commons.net

Java使用comms-net jar包完成ftp文件上传进度的检测功能

本文章只讲述大致的思路与本次功能对应的一些开发环境,具体实现请结合自己的开发情况,仅供参考,如果有不对的地方,欢迎大家指出! 准备环境:JDK1.7 OR 1.8.eclipse.ftp服务器(可自行搭建).comms-net jar包3.3版本的.其余的就不详细列举了. 1.在现实开发中ftp服务器和项目的部署服务器基本不会是同一台,所以基础springmvc的文件上传进度获取,只能获取到文件的二进制流到达项目后台的进度.对于真实的ftp文件上传进度,需要使用comms-net提供的监听器来实

PHP多文件上传操作

在前一篇文章里讲到了关于PHP文件上传原理和简单操作举例是单文件上传. http://www.cnblogs.com/lichenwei/p/3879566.html 其实多文件上传和单文件上传大同小异,原理都是一样的,只是在代码上做了点小技巧. 首先还是index.html上传表单,只是把之前上传文件表单里的file更改成了file[] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "ht

【问题分析】FTP文件上传与下载

问题描述:通常应用服务器与文件服务器分别在不同的机器上,涉及到文件的上传与下载.通过建立网络映射盘的形式,将文件服务器保存文件的文件夹映射到应用服务器的某个盘符下,经过试验,在tomcat下两台笔记本是可以实现的,但是在生产环境的websphere下试验,经过多番尝试,仍然实现不了. 问题分析:采用FTP的方式实现文件的上传与下载功能,在Java代码中编写客户端的上传与下载,在文件服务器上,直接装一个FTP服务器软件即可.注意生产环境的防火墙以及客户是否允许使用FTP. 解决方案: 工程中导入J

python-selenium -- 文件上传操作

一.文件上传操作 win32gui.FindWindow(IPClassName,IPWindowName) 自顶层窗口开始寻找匹配条件的窗口,并返回这个窗口的句柄: IPClassName:类名,在Spy++里能够看到: IPWindowName:窗口名,标题栏上能看到的名字 win32gui.FindWindowEx(hwndParent=0,hwndChildAfter=0,IPszClassName=None,IPszWindowName=None) 搜索类名和窗体名匹配的窗体,并返回这

【FTP】FTP文件上传下载-支持断点续传

Jar包:apache的commons-net包: 支持断点续传 支持进度监控(有时出不来,搞不清原因) 相关知识点 编码格式: UTF-8等; 文件类型: 包括[BINARY_FILE_TYPE(常用)]和[ASCII_FILE_TYPE]两种; 数据连接模式:一般使用LocalPassiveMode模式,因为大部分客户端都在防火墙后面: 1. LocalPassiveMode:服务器端打开数据端口,进行数据传输: 2. LocalActiveMode:客户端打开数据端口,进行数据传输: 系统