加入收藏 | 设为首页 | 会员中心 | 我要投稿 聊城站长网 (https://www.0635zz.com/)- 智能语音交互、行业智能、AI应用、云计算、5G!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

有关c#连接ftp进行上传下载实现原理及代码

发布时间:2023-04-10 14:12:13 所属栏目:语言 来源:
导读:代码如下:

using System;

using System.Collections.Generic;

using System.Text;

using System.Net;

using System.IO;

namespace ftponload

{

class Program

{

static voi
代码如下:
 
using System;
 
using System.Collections.Generic;
 
using System.Text;
 
using System.Net;
 
using System.IO;
 
namespace ftponload
 
{
 
class Program
 
{
 
static void Main(string[] args)
 
{
 
//上传文件的方法
 
onload("D://outPut.txt");
 
//下载文件的方法
 
fload();
 
}
 
public static void onload(string file)
 
{
 
//构造一个web服务器的请求对象
 
FtpWebRequest ftp;
 
//实例化一个文件对象
 
FileInfo f = new FileInfo(file);
 
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://192.168.0.150/" + f.Name));
 
//创建用户名和密码
 
ftp.Credentials = new NetworkCredential("123", "123");
 
ftp.KeepAlive = false;
 
ftp.Method = WebRequestMethods.Ftp.UploadFile;
 
ftp.UseBinary = true;
 
ftp.ContentLength = f.Length;
 
int buffLength = 20480;
 
byte[] buff = new byte[buffLength];
 
int contentLen;
 
try
 
{
 
//获得请求对象的输入流
 
FileStream fs = f.OpenRead();
 
Stream sw = ftp.GetRequestStream();
 
contentLen = fs.Read(buff, 0, buffLength);
 
while (contentLen != 0)
 
{
 
sw.Write(buff, 0, contentLen);
 
contentLen = fs.Read(buff, 0, buffLength);
 
}
 
sw.Close();
 
fs.Close();
 
}
 
catch (Exception e)
 
{
 
Console.WriteLine(e.Message);
 
}
 
}
 
public static void fload()
 
{
 
FtpWebRequest ftp;
 
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://192.168.0.6/连接到你指定的文件"));
 
//指定用户名和密码
 
ftp.Credentials = new NetworkCredential("123", "123456");
 
WebResponse wr = ftp.GetResponse();
 
StreamReader sr = new StreamReader(wr.GetResponseStream(),System.Text.Encoding.Default);
 
string s = sr.ReadLine();
 
while(s.Equals(""))
 
{
 
s = sr.ReadLine();
 
}
 
}
 
}
 
}
 
 

(编辑:聊城站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!