c# FTP上传文件
哪个问题我已经解决了,现在还有一个问题想请教您,我想用C#实现单点击按钮将d://1/下的1.txt以ftp方式上传,用户名是aa,密码是aa123,该怎么写呀麻烦各位写...
哪个问题我已经解决了,现在还有一个问题想请教您,我想用C#实现单点击按钮将d://1/下的1.txt以ftp方式上传,用户名是aa,密码是aa123,该怎么写呀
麻烦各位写详细些,我是处学者
你好:我按你写的试了,我本来的意思是将你写的代码放到一个单击事件中,但一放进去就提示一堆错,最后我放到了单击事件的外面(既单击事件所对应的{}之后,)提示错误1:字段初始值设定项无法引用非静态字段、方法或属性“WindowsFormsApplication1.Form1.UploadFun(string, string)” 和错误2:当前上下文中不存在名称“getCredential” 该怎么要改呀???? 展开
麻烦各位写详细些,我是处学者
你好:我按你写的试了,我本来的意思是将你写的代码放到一个单击事件中,但一放进去就提示一堆错,最后我放到了单击事件的外面(既单击事件所对应的{}之后,)提示错误1:字段初始值设定项无法引用非静态字段、方法或属性“WindowsFormsApplication1.Form1.UploadFun(string, string)” 和错误2:当前上下文中不存在名称“getCredential” 该怎么要改呀???? 展开
推荐于2016-11-05
展开全部
C# ftp上传,参考如下:
/// <summary>
/// 上传文件
/// </summary> /
// <param name="fileinfo">需要上传的文件</param>
/// <param name="targetDir">目标路径</param>
/// <param name="hostname">ftp地址</param> /
// <param name="username">ftp用户名</param> /
// <param name="password">ftp密码</param>
public static void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password)
{ //1. check target
string target;
if (targetDir.Trim() == "")
{ return; }
target = Guid.NewGuid().ToString();
//使用临时文件名
string URI = "FTP://" + hostname + "/" + targetDir + "/" + target;
///WebClient webcl = new WebClient();
System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
//设置FTP命令 设置所要执行的FTP命令,
//ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表
ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
//指定文件传输的数据类型
ftp.UseBinary = true;
ftp.UsePassive = true; //告诉ftp文件大小
ftp.ContentLength = fileinfo.Length;
//缓冲大小设置为2KB
const int BufferSize = 2048;
byte[] content = new byte[BufferSize - 1 + 1];
int dataRead; //打开一个文件流 (System.IO.FileStream) 去读上传的文件
using (FileStream fs = fileinfo.OpenRead())
{
try { //把上传的文件写入流
using (Stream rs = ftp.GetRequestStream())
{ do
{ //每次读文件流的2KB
dataRead = fs.Read(content, 0, BufferSize); rs.Write(content, 0, dataRead); }
while (!(dataRead < BufferSize)); rs.Close(); } }
catch (Exception ex) { } finally { fs.Close(); } }
ftp = null; //设置FTP命令
ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名
ftp.RenameTo = fileinfo.Name; try { ftp.GetResponse(); }
catch (Exception ex)
{
ftp = GetRequest(URI, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除
ftp.GetResponse(); throw ex; } finally
{
//fileinfo.Delete(); } // 可以记录一个日志 "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." );
ftp = null;
#region
/***** *FtpWebResponse * ****/ //FtpWebResponse ftpWebResponse = (FtpWebResponse)ftp.GetResponse();
#endregion
}
/// <summary>
/// 下载文件
/// </summary>
/// <param name="localDir">下载至本地路径</param>
/// <param name="FtpDir">ftp目标文件路径</param>
/// <param name="FtpFile">从ftp要下载的文件名</param>
/// <param name="hostname">ftp地址即IP</param>
/// <param name="username">ftp用户名</param>
/// <param name="password">ftp密码</param>
public static void DownloadFile(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password)
{
string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile;
string tmpname = Guid.NewGuid().ToString();
string localfile = localDir + @"\" + tmpname;
System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary = true;
ftp.UsePassive = false;
using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
//loop to read & write to file
using (FileStream fs = new FileStream(localfile, FileMode.CreateNew))
{
try
{
byte[] buffer = new byte[2048];
int read = 0;
do
{
read = responseStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, read);
} while (!(read == 0));
responseStream.Close();
fs.Flush();
fs.Close();
}
catch (Exception)
{
//catch error and delete file only partially downloaded
fs.Close();
//delete target file as it's incomplete
File.Delete(localfile);
throw;
}
}
responseStream.Close();
}
response.Close();
}
try
{
File.Delete(localDir + @"\" + FtpFile);
File.Move(localfile, localDir + @"\" + FtpFile);
ftp = null;
ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile;
ftp.GetResponse();
}
catch (Exception ex)
{
File.Delete(localfile);
throw ex;
}
// 记录日志 "从" + URI.ToString() + "下载到" + localDir + @"\" + FtpFile + "成功." );
ftp = null;
}
/// <summary>
/// 搜索远程文件
/// </summary>
/// <param name="targetDir"></param>
/// <param name="hostname"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="SearchPattern"></param>
/// <returns></returns>
public static List<string> ListDirectory(string targetDir, string hostname, string username, string password, string SearchPattern)
{
List<string> result = new List<string>();
try
{
string URI = "FTP://" + hostname + "/" + targetDir + "/" + SearchPattern;
System.Net.FtpWebRequest ftp = GetRequest(URI, username, password);
ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectory;
ftp.UsePassive = true;
ftp.UseBinary = true;
string str = GetStringResponse(ftp);
str = str.Replace("\r\n", "\r").TrimEnd('\r');
str = str.Replace("\n", "\r");
if (str != string.Empty)
result.AddRange(str.Split('\r'));
return result;
}
catch { }
return null;
}
private static string GetStringResponse(FtpWebRequest ftp)
{
//Get the result, streaming to a string
string result = "";
using (FtpWebResponse response = (FtpWebResponse)ftp.GetResponse())
{
long size = response.ContentLength;
using (Stream datastream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(datastream, System.Text.Encoding.Default))
{
result = sr.ReadToEnd();
sr.Close();
}
datastream.Close();
}
response.Close();
}
return result;
}
/// 在ftp服务器上创建目录
/// </summary>
/// <param name="dirName">创建的目录名称</param>
/// <param name="ftpHostIP">ftp地址</param>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
public void MakeDir(string dirName,string ftpHostIP,string username,string password)
{
try
{
string uri = "ftp://" + ftpHostIP + "/" + dirName;
System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 删除目录
/// </summary>
/// <param name="dirName">创建的目录名称</param>
/// <param name="ftpHostIP">ftp地址</param>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
public void delDir(string dirName, string ftpHostIP, string username, string password)
{
try
{
string uri = "ftp://" + ftpHostIP + "/" + dirName;
System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
ftp.Method = WebRequestMethods.Ftp.RemoveDirectory;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 文件重命名
/// </summary>
/// <param name="currentFilename">当前目录名称</param>
/// <param name="newFilename">重命名目录名称</param>
/// <param name="ftpServerIP">ftp地址</param>
/// <param name="username">用户名</param>
/// <param name="password">密码</param>
public void Rename(string currentFilename, string newFilename, string ftpServerIP, string username, stringpassword)
{
try
{
FileInfo fileInf = new FileInfo(currentFilename);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
System.Net.FtpWebRequest ftp = GetRequest(uri, username, password);
ftp.Method = WebRequestMethods.Ftp.Rename;
ftp.RenameTo = newFilename;
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
response.Close();
}
catch (Exception ex) { MessageBox.Show(ex.Message); } }
private static FtpWebRequest GetRequest(string URI, string username, string password)
{
//根据服务器信息FtpWebRequest创建类的对象
FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI);
//提供身份验证信息
result.Credentials = new System.Net.NetworkCredential(username, password);
//设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true
result.KeepAlive = false;
return result;
}
展开全部
GetRequestStream();
try
{
FtpWebRequest
uploadRequest
=
(FtpWebRequest)WebRequest.Ftp;调用以下函数
private
FtpStatusCode
UploadFun(string
fileName,
0;aa123".Create(uploadUrl).你可以直接使用;ftp;目录/
fileStream
=
File;
requestStream;1,如果还有问题可以继续联系.Close().Undefined;错误2
requestStream
=
uploadRequest.Close();
NetworkCredential
nc
=
new
NetworkCredential().Read(buffer;/域名/.Write(buffer.Close();
int
bytesRead.txt".Length);.GetResponse(),
string
uploadUrl)
{
Stream
requestStream
=
null;
using
System.Method
=
WebRequestMethods!=
null)
requestStream!=
null)
fileStream;
}
catch
(UriFormatException
ex)
{
}
catch
(IOException
ex)
{
}
catch
(WebException
ex)
{
}
finally
{
if
(uploadResponse
;/
uploadResponse
=
(FtpWebResponse)uploadRequest;调用例子
FtpStatusCode
status
=
UploadFun(@",
FileMode.StatusCode;
}
return
FtpStatusCode;.Open(fileName:/.UserName
=
".UploadFile,
bytesRead).
using
System,
"
/.Net;
if
(bytesRead
==
0)
break.Open););1\
while
(true)
{
bytesRead
=
fileStream;
if
(requestStream
;
return
uploadResponse.Proxy
=
null;
nc;
/:\
}
requestStream.Password
=
".Close();d;
uploadRequest.IO;
FtpWebResponse
uploadResponse
=
null;
uploadRequest;保存文件名"/修改getCredential()!=
null)
uploadResponse;
}
/
if
(fileStream
,
buffer;
FileStream
fileStream
=
null;aa"
uploadRequest.Credentials
=
nc,
0;
nc;
byte[]
buffer
=
new
byte[1024]我摘录一段给你;;/
try
{
FtpWebRequest
uploadRequest
=
(FtpWebRequest)WebRequest.Ftp;调用以下函数
private
FtpStatusCode
UploadFun(string
fileName,
0;aa123".Create(uploadUrl).你可以直接使用;ftp;目录/
fileStream
=
File;
requestStream;1,如果还有问题可以继续联系.Close().Undefined;错误2
requestStream
=
uploadRequest.Close();
NetworkCredential
nc
=
new
NetworkCredential().Read(buffer;/域名/.Write(buffer.Close();
int
bytesRead.txt".Length);.GetResponse(),
string
uploadUrl)
{
Stream
requestStream
=
null;
using
System.Method
=
WebRequestMethods!=
null)
requestStream!=
null)
fileStream;
}
catch
(UriFormatException
ex)
{
}
catch
(IOException
ex)
{
}
catch
(WebException
ex)
{
}
finally
{
if
(uploadResponse
;/
uploadResponse
=
(FtpWebResponse)uploadRequest;调用例子
FtpStatusCode
status
=
UploadFun(@",
FileMode.StatusCode;
}
return
FtpStatusCode;.Open(fileName:/.UserName
=
".UploadFile,
bytesRead).
using
System,
"
/.Net;
if
(bytesRead
==
0)
break.Open););1\
while
(true)
{
bytesRead
=
fileStream;
if
(requestStream
;
return
uploadResponse.Proxy
=
null;
nc;
/:\
}
requestStream.Password
=
".Close();d;
uploadRequest.IO;
FtpWebResponse
uploadResponse
=
null;
uploadRequest;保存文件名"/修改getCredential()!=
null)
uploadResponse;
}
/
if
(fileStream
,
buffer;
FileStream
fileStream
=
null;aa"
uploadRequest.Credentials
=
nc,
0;
nc;
byte[]
buffer
=
new
byte[1024]我摘录一段给你;;/
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
我摘录一段给你.你可以直接使用,如果还有问题可以继续联系.
using System.Net;
using System.IO;
//调用以下函数
private FtpStatusCode UploadFun(string fileName, string uploadUrl)
{
Stream requestStream = null;
FileStream fileStream = null;
FtpWebResponse uploadResponse = null;
try
{
FtpWebRequest uploadRequest =
(FtpWebRequest)WebRequest.Create(uploadUrl);
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;
uploadRequest.Proxy = null;
NetworkCredential nc = new NetworkCredential();
nc.UserName = "aa";
nc.Password = "aa123";
uploadRequest.Credentials = nc; //修改getCredential();错误2
requestStream = uploadRequest.GetRequestStream();
fileStream = File.Open(fileName, FileMode.Open);
byte[] buffer = new byte[1024];
int bytesRead;
while (true)
{
bytesRead = fileStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
requestStream.Write(buffer, 0, bytesRead);
}
requestStream.Close();
uploadResponse = (FtpWebResponse)uploadRequest.GetResponse();
return uploadResponse.StatusCode;
}
catch (UriFormatException ex)
{
}
catch (IOException ex)
{
}
catch (WebException ex)
{
}
finally
{
if (uploadResponse != null)
uploadResponse.Close();
if (fileStream != null)
fileStream.Close();
if (requestStream != null)
requestStream.Close();
}
return FtpStatusCode.Undefined;
}
//调用例子
FtpStatusCode status = UploadFun(@"d:\1\1.txt", "ftp://域名/目录/保存文件名");
using System.Net;
using System.IO;
//调用以下函数
private FtpStatusCode UploadFun(string fileName, string uploadUrl)
{
Stream requestStream = null;
FileStream fileStream = null;
FtpWebResponse uploadResponse = null;
try
{
FtpWebRequest uploadRequest =
(FtpWebRequest)WebRequest.Create(uploadUrl);
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;
uploadRequest.Proxy = null;
NetworkCredential nc = new NetworkCredential();
nc.UserName = "aa";
nc.Password = "aa123";
uploadRequest.Credentials = nc; //修改getCredential();错误2
requestStream = uploadRequest.GetRequestStream();
fileStream = File.Open(fileName, FileMode.Open);
byte[] buffer = new byte[1024];
int bytesRead;
while (true)
{
bytesRead = fileStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
requestStream.Write(buffer, 0, bytesRead);
}
requestStream.Close();
uploadResponse = (FtpWebResponse)uploadRequest.GetResponse();
return uploadResponse.StatusCode;
}
catch (UriFormatException ex)
{
}
catch (IOException ex)
{
}
catch (WebException ex)
{
}
finally
{
if (uploadResponse != null)
uploadResponse.Close();
if (fileStream != null)
fileStream.Close();
if (requestStream != null)
requestStream.Close();
}
return FtpStatusCode.Undefined;
}
//调用例子
FtpStatusCode status = UploadFun(@"d:\1\1.txt", "ftp://域名/目录/保存文件名");
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询