FTP上传、下载(简单小例子)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net; namespace FTPConsoleApplication
{
class Program
{
static void Main(string[] args)
{
//测试
//DownloadFtp("优课.png");
//UploadFtp("FTPConsoleApplication.exe.config");
//SystemLog.logger("OK");
} public static FtpStatusCode UploadFileInFTP(string filename)
{
Stream requestStream = null;
FileStream fileStream = null;
FtpWebResponse uploadResponse = null;
FtpWebRequest uploadRequest = null;
string serverIP;
string userName;
string password;
string uploadurl; try
{
serverIP = System.Configuration.ConfigurationManager.AppSettings["FTPServerIP"];
userName = System.Configuration.ConfigurationManager.AppSettings["UserName"];
password = System.Configuration.ConfigurationManager.AppSettings["Password"];
uploadurl = "ftp://" + serverIP + "/" + Path.GetFileName(filename);
uploadRequest = (FtpWebRequest)WebRequest.Create(uploadurl);
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;
uploadRequest.Proxy = null;
NetworkCredential nc = new NetworkCredential();
nc.UserName = userName;
nc.Password = password;
uploadRequest.Credentials = nc;
requestStream = uploadRequest.GetRequestStream();
fileStream = File.Open(filename, FileMode.Open); byte[] buffer = new byte[];
int bytesRead; while (true)
{
bytesRead = fileStream.Read(buffer, , buffer.Length);
if (bytesRead == )
{
break;
}
requestStream.Write(buffer, , bytesRead);
} requestStream.Close();
uploadResponse = (FtpWebResponse)uploadRequest.GetResponse();
return uploadResponse.StatusCode;
}
catch (Exception e)
{
SystemLog.logger(e.InnerException.Message);
}
finally
{
if (uploadResponse != null)
{
uploadResponse.Close();
}
if (fileStream != null)
{
fileStream.Close();
}
if (requestStream != null)
{
requestStream.Close();
} }
return FtpStatusCode.Undefined;
} public static int UploadFtp(string filename)
{
FtpWebRequest reqFTP = null;
string serverIP;
string userName;
string password;
string url; try
{
FileInfo fileInf = new FileInfo(filename);
serverIP = System.Configuration.ConfigurationManager.AppSettings["FTPServerIP"];
userName = System.Configuration.ConfigurationManager.AppSettings["UserName"];
password = System.Configuration.ConfigurationManager.AppSettings["Password"];
url = "ftp://" + serverIP + "/" + Path.GetFileName(filename); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
reqFTP.Credentials = new NetworkCredential(userName, password);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length; int buffLength = ;
byte[] buff = new byte[buffLength];
int contentLen; FileStream fs = fileInf.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite); Stream strm = reqFTP.GetRequestStream(); contentLen = fs.Read(buff, , buffLength); while (contentLen != )
{ strm.Write(buff, , contentLen);
contentLen = fs.Read(buff, , buffLength);
} strm.Close();
fs.Close();
return ;
}
catch (Exception ex)
{
if (reqFTP != null)
{
reqFTP.Abort();
}
SystemLog.logger(ex.InnerException.Message);
return -;
}
} public static int DownloadFtp(string filename)
{
FtpWebRequest reqFTP;
string serverIP;
string userName;
string password;
string url; try
{
serverIP = System.Configuration.ConfigurationManager.AppSettings["FTPServerIP"];
userName = System.Configuration.ConfigurationManager.AppSettings["UserName"];
password = System.Configuration.ConfigurationManager.AppSettings["Password"];
url = "ftp://" + serverIP + "/" + Path.GetFileName(filename); FileStream outputStream = new FileStream(filename, FileMode.Create);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Credentials = new NetworkCredential(userName, password);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = ;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, , bufferSize);
while (readCount > )
{
outputStream.Write(buffer, , readCount);
readCount = ftpStream.Read(buffer, , bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
return ;
}
catch (Exception ex)
{
SystemLog.logger(ex.InnerException.Message);
return -;
}
} public class SystemLog
{ public static bool logger(string message)
{
try
{
DateTime timeNow = DateTime.Now;
string logPath = System.Configuration.ConfigurationManager.AppSettings["LogPath"];
string logSwitch = System.Configuration.ConfigurationManager.AppSettings["LogSwitch"];
if (logSwitch == "")
{
string logFullPath = Path.Combine(System.Environment.CurrentDirectory,logPath);
DirectoryInfo dirInfo = new DirectoryInfo(logFullPath);
if (!dirInfo.Exists)
{
dirInfo.Create();
} Encoding encoding = Encoding.GetEncoding("gb2312");
byte[] info = encoding.GetBytes("[ " + timeNow.ToString("yyyy-MM-dd HH:mm:ss") + " ] " + message + "\n"); //转换编码成字节串 if (!logPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
logPath = logPath + Path.DirectorySeparatorChar.ToString();
} using (FileStream fs = System.IO.File.Open(logPath + timeNow.ToString("yyyy_MM_dd") + ".txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
fs.Write(info, , info.Length);
//以ASCII方式编写
using (StreamWriter w = new StreamWriter(fs, Encoding.ASCII))
{
w.Flush();
w.Close();
} fs.Close();
}
}
return true;
}
catch (Exception e)
{
return false;
}
}
} } }
FTP上传、下载(简单小例子)的更多相关文章
- JAVA 实现FTP上传下载(sun.net.ftp.FtpClient)
package com.why.ftp; import java.io.DataInputStream; import java.io.File; import java.io.FileInputSt ...
- windows系统下ftp上传下载和一些常用命令
先假设一个ftp地址 用户名 密码 FTP Server: home4u.at.china.com User: yepanghuang Password: abc123 打开windows的开始菜单, ...
- windows下ftp上传下载和一些常用命令
先假设一个ftp地址 用户名 密码 FTP Server: home4u.at.china.com User: yepanghuang Password: abc123 打开windows的开始菜单, ...
- FTP上传下载工具(FlashFXP) v5.5.0 中文版
软件名称: FTP上传下载工具(FlashFXP) 软件语言: 简体中文 授权方式: 免费试用 运行环境: Win 32位/64位 软件大小: 7.4MB 图片预览: 软件简介: FlashFXP 是 ...
- 高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)
前言 最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种. 第一种是单例模式的类. 第二种是另外定义一个Service,直接通过Service来实现ftp的上 ...
- C# -- FTP上传下载
C# -- FTP上传下载 1. C#实现FTP下载 private static void TestFtpDownloadFile(string strFtpPath, string strFile ...
- Java.ftp上传下载
1:jar的maven的引用: 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="ht ...
- python之实现ftp上传下载代码(含错误处理)
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之实现ftp上传下载代码(含错误处理) #http://www.cnblogs.com/kait ...
- python之模块ftplib(实现ftp上传下载代码)
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之模块ftplib(实现ftp上传下载代码) #需求:实现ftp上传下载代码(不含错误处理) f ...
- java客户端调用ftp上传下载文件
1:java客户端上传,下载文件. package com.li.utils; import java.io.File; import java.io.FileInputStream; import ...
随机推荐
- BZOJ1801 [Ahoi2009]chess 中国象棋 动态规划
欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - BZOJ1801 题意概括 在N行M列的棋盘上,放若干个炮可以是0个,使得没有任何一个炮可以攻击另一个炮. 请 ...
- 【noip模拟赛5】细菌
描述 近期,农场出现了D(1<=D<=15)种细菌.John要从他的 N(1<=N<=1,000)头奶牛中尽可能多地选些产奶.但是如果选中的奶牛携带了超过 K (1<=K ...
- django csrf_protect及浏览器同源策略
1.django在检测post行为时会有诸多的限制. 为了防止跨域请求伪造安全 参考:http://www.qttc.net/201209211.html https://www.cnblogs. ...
- 在VS Code中对Python进行单元测试
在VS Code中对Python进行单元测试 Python扩展支持使用Python的内置unittest框架以及pytest和Nose进行单元测试.要使用pytest和Nose,必须将它们安装到当前的 ...
- HDU 5391 Zball in Tina Town【威尔逊定理】
<题目链接> Zball in Tina Town Problem Description Tina Town is a friendly place. People there care ...
- POJ 1182 食物链 【带权并查集】
<题目链接> 题目大意: 动物王国中有三类动物A,B,C,这三类动物的食物链构成了有趣的环形.A吃B, B吃C,C吃A. 现有N个动物,以1-N编号.每个动物都是A,B,C中的一种,但是我 ...
- P2789 直线交点数
P2789 直线交点数分成两种情况,一种是平行直线,一种是自由直线,在自由直线中可以存在平行直线,但是不能和第一组的直线平行.自由直线和平行直线的交点是i*(n-i). #include<ios ...
- java8 Optional正确使用姿势
Java 8 如何正确使用 Optional import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; ...
- STL中实现 iterator trail 的编程技巧
STL中实现 iterator trail 的编程技巧 <泛型编程和 STL>笔记及思考. 这篇文章主要记录在 STL 中迭代器设计过程中出现的编程技巧,围绕的 STL 主题为 (迭代器特 ...
- asp.net core for vs code
1,命令 2,模板 3,更换启动浏览器 4,vscode使用nuget 5,使用ef migration 6,配置.net core的工作目录 7,使用dotnet ef migrations命令 8 ...