65.9K
CodeProject 正在变化。 阅读更多。
Home

FtpWebRequest

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2投票s)

2013 年 10 月 11 日

CPOL

1分钟阅读

viewsIcon

47096

FtpWebRequest 类允许您以编程方式创建到 FTP 服务器的 FTP 连接并传输文件。如果您

FtpWebRequest

FtpWebRequest 类允许您以编程方式创建到 FTP 服务器的 FTP 连接并传输文件。如果您有兴趣使用 FtpWebRequest 类将文件上传到服务器,这里有一个代码示例

FtpWebRequest ftpRequest;

FtpWebResponse ftpResponse;

 

try

{

    //建立与服务器连接所需的设置

    this.ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://ServerIP/FileName"));

    this.ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;

    this.ftpRequest.Proxy = null;

    this.ftpRequest.UseBinary = true;

    this.ftpRequest.Credentials = new NetworkCredential("UserName", "Password");

 

    //选择要上传的文件

    FileInfo ff = new FileInfo("文件本地路径和文件名");//例如:c:\\Test.txt

    byte[] fileContents = new byte[ff.Length];

 

    //在使用后立即销毁对象

    using (FileStream fr = ff.OpenRead())

    {

        fr.Read(fileContents, 0, Convert.ToInt32(ff.Length));

    }

 

    using (Stream writer = ftpRequest.GetRequestStream())

    {

        writer.Write(fileContents, 0, fileContents.Length);

    }

    //获取上传操作的 FtpWebResponse

    this.ftpResponse = (FtpWebResponse)this.ftpRequest.GetResponse();

    Response.Write(this.ftpResponse.StatusDescription); //显示响应

}

catch (WebException webex)

{

    this.Message = webex.ToString();

}

 
 

链接

http://msdn.microsoft.com/en-us/library/system.net.ftpwebrequest.aspx

 
© . All rights reserved.