首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C# winform程序 如何向ftp文件服务器下传文件? 。

2012-10-17 
C# winform程序 怎么向ftp文件服务器上传文件?? 在线等。。。C# winform程序 怎么向ftp文件服务器上传文件?我

C# winform程序 怎么向ftp文件服务器上传文件?? 在线等。。。
C# winform程序 怎么向ftp文件服务器上传文件? 
我用的方法:System.IO.File.Move(sourcepath, @"ftp:\\177.19.1.8\kaikake\TEST\" + filename); 
(比如ftp:\\177.19.1.8\kaikake\TEST\是一文件服务器地址) 
但是 提示错误信息: 不支持这种路径格式 应该怎么写?? 请高人指教!! 谢谢了 
还需要在程序中设置登陆名和密码吗? 如果需要,应该怎么设置?

[解决办法]
在.net 2.0 中添加了对许多ftp的支持,使用ftp变得非常简单了。

首先,WebClient支以已经开始支持ftp协议了。

比如说要从远程服务器上下载文件,只要使用两条命令就可以完成。

WebClient webClient = new WebClient();

webClient.DownloadFile("ftp://username:password@192.168.1.1/123.txt", @"f:\123.txt");

上传文件到远程服务器也是一样简单。

WebClient webClient = new WebClient();

webClient.UploadFile("ftp://username:password@192.168.1.1/456.txt", @"f:\123.txt");
[解决办法]
//ftp方式上传
public static int UploadFtp(string filePath, string filename, string ftpServerIP, string ftpUserID, string ftpPassword)
{

FileInfo fileInf = new FileInfo(filePath + "\\" + filename);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
FtpWebRequest reqFTP;


// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));
try
{

// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
reqFTP.KeepAlive = false;

// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

// Specify the data transfer type.
reqFTP.UseBinary = true;

// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;

// The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;

// Opens a file stream (System.IO.FileStream) to read the file to be uploaded
//FileStream fs = fileInf.OpenRead();
FileStream fs = fileInf.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite);


// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();

// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);

// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}

// Close the file stream and the Request Stream
strm.Close();
fs.Close();
return 0;
}
catch (Exception ex)
{
reqFTP.Abort();
Logging.WriteError(ex.Message + ex.StackTrace);
return -2;
}
}
//ftp方式下载


public static int DownloadFtp(string filePath, string fileName, string ftpServerIP, string ftpUserID, string ftpPassword)
{
FtpWebRequest reqFTP;
try
{
//filePath = <<The full path where the file is to be created.>>, 
//fileName = <<Name of the file to be created(Need not be the name of the file on FTP server).>>
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + 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 0;
}
catch (Exception ex)
{
Logging.WriteError(ex.Message + ex.StackTrace);
return -2;
}
}
[解决办法]

探讨
//ftp方式上传
public static int UploadFtp(string filePath, string filename, string ftpServerIP, string ftpUserID, string ftpPassword)
{

FileInfo fileInf = new FileInfo(filePath + "\\" + filename);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
FtpWebRequest reqFTP;




[解决办法]
(1)前面提到的Web Services,就是一种很好的方法,通过编写一个WebMethod,包含有 byte[] 类型的参数,然后调用Web Services的方法,文件内容就会以Base64编码传到服务器上,然后重新保存即可。



[WebMethod]
public void UploadFile(byte[] content,string filename){
Stream sw = new StreamWriter(...);
sw.Close();
}
当然,这种通过Base64编码的方法效率比较低,那么可以采用WSE,支持附件,并以2进制形式传送,效率会更高。
(2)除了通过WebService,另外一种更简单的方法就是通过WebClient或者HttpWebRequest来模拟HTTP的POST动作来实现。这时候首先需要编写一个asp.net web form来响应上传,代码如下:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="UploadFileWeb.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
 <head>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
 </head>
 <body>
<form id="Form1" method="post" runat="server">
</form>
 </body>
</html>



using System;
using System.Collections;


using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;



namespace UploadFileWeb
{
 /// <summary>
 /// WebForm1 的摘要说明。
 /// </summary>
 public class WebForm1 : System.Web.UI.Page
 {
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
foreach( string f in Request.Files.AllKeys)
{
HttpPostedFile file = Request.Files[f];
file.SaveAs(@"D:\Temp\" + file.FileName);
}
if( Request.Params["testKey"] != null )
{
Response.Write(Request.Params["testKey"]);
}
}

#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
  
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
 }
}




其实这个页面跟我们平常写的asp.net上传文件代码是一样的,在Web 页的Request对象中包含有Files这个对象,里面就包含了通过POST方式上传的所有文件的信息,这时所需要做的就是调用 Request.Files[i].SaveAs方法。



但是怎么让才能在WinForm里面模拟想Web Form POST 数据呢?System.Net命名空间里面提供了两个非常有用的类,一个是WebClient,另外一个是HttpWebRequest类。如果我们不需要通过代理服务器来上传文件,那么非常简单,只需要简单的调用WebClient.UploadFile方法就能实现上传文件:

private void button1_Click(object sender, System.EventArgs e)
{
WebClient myWebClient = new WebClient();
 
myWebClient.UploadFile("http://localhost/UploadFileWeb/WebForm1.aspx","POST",@"D:\Temp\Java\JavaStart\JavaStart2.exe");
}




是不是觉得很简单呢?确实就这么简单。



但是如果要通过代理服务器上传又怎么办呢?那就需要使用到HttpWebRequest,但是该类没有Upload方法,但是幸运的是我们通过Reflector反编译了WebClient.UploadFile方法后,我们发现其内部也是通过WebRequest来实现的,代码如下:
public byte[] UploadFile(string address, string method, string fileName)
{
string text1;
string text2;
WebRequest request1;
string text3;
byte[] buffer1;
byte[] buffer2;
long num1;
byte[] buffer3;
int num2;
WebResponse response1;
byte[] buffer4;
DateTime time1;
long num3;
string[] textArray1;
FileStream stream1 = null;
try
{
fileName = Path.GetFullPath(fileName);
time1 = DateTime.Now;
num3 = time1.Ticks;
text1 = "---------------------" + num3.ToString("x");
if (this.m_headers == null)

{
this.m_headers = new WebHeaderCollection();
}
text2 = this.m_headers["Content-Type"];
if (text2 != null)
{
if (text2.ToLower(CultureInfo.InvariantCulture).StartsWith("multipart/"))
{
throw new WebException(SR.GetString("net_webclient_Multipart"));
}
}
else
{
text2 = "application/octet-stream";
}
this.m_headers["Content-Type"] = "multipart/form-data; boundary=" + text1;
this.m_responseHeaders = null;
stream1 = new FileStream(fileName, FileMode.Open, FileAccess.Read);
request1 = WebRequest.Create(this.GetUri(address));
request1.Credentials = this.Credentials;
this.CopyHeadersTo(request1);
request1.Method = method;


textArray1 = new string[7];
textArray1[0] = "--";
textArray1[1] = text1;
textArray1[2] = "\r\nContent-Disposition: form-data; name=\"file\"; filename=\"";
textArray1[3] = Path.GetFileName(fileName);
textArray1[4] = "\"\r\nContent-Type: ";
textArray1[5] = text2; textArray1[6] = "\r\n\r\n";
text3 = string.Concat(textArray1);
buffer1 = Encoding.UTF8.GetBytes(text3);
buffer2 = Encoding.ASCII.GetBytes("\r\n--" + text1 + "\r\n");
num1 = 9223372036854775807;
try
{
num1 = stream1.Length;
request1.ContentLength = ((num1 + ((long) buffer1.Length)) + ((long) buffer2.Length));
}
catch
{
}
buffer3 = new byte[Math.Min(((int) 8192), ((int) num1))];
using (Stream stream2 = request1.GetRequestStream())
{
stream2.Write(buffer1, 0, buffer1.Length);
do
{
num2 = stream1.Read(buffer3, 0, buffer3.Length);
if (num2 != 0)
{
stream2.Write(buffer3, 0, num2);
}
}
while ((num2 != 0));
stream2.Write(buffer2, 0, buffer2.Length); }
stream1.Close();
stream1 = null;
response1 = request1.GetResponse();
this.m_responseHeaders = response1.Headers;
return this.ResponseAsBytes(response1);
}
catch (Exception exception1)
{
if (stream1 != null)
{
stream1.Close();
stream1 = null;
}
if ((exception1 is WebException) || (exception1 is SecurityException))
{
throw;
}
throw new WebException(SR.GetString("net_webclient"), exception1);
}
return buffer4;
}
 



[解决办法]
FtpClient ftptest=new FtpClient();
ftptest.Upload(this.txtfilename.Text,true);

热点排行