C#设置通过代理访问ftp服务器

时间:2023-03-08 19:11:09
C#设置通过代理访问ftp服务器

C#设置通过代理访问ftp服务器

// 创建FTP连接

private FtpWebRequest CreateFtpWebRequest(string uri, string requestMethod)
{
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(uri);
request.Credentials = networkCredential;
request.KeepAlive = true;
request.UseBinary = true;
request.Method = requestMethod;
//设置代理(设置为空,默认使用ie的代理设置)
request.Proxy = GlobalProxySelection.GetEmptyWebProxy();
return request;
}

// 获取服务器返回的响应体
private FtpWebResponse GetFtpResponse(FtpWebRequest request)
{
FtpWebResponse response = null;
try
{
response = (FtpWebResponse)request.GetResponse();
lstbxFtpState.Items.Add("验证完毕,服务器回应信息:[" + response.WelcomeMessage + "]");
lstbxFtpState.Items.Add("正在连接:[ " + response.BannerMessage + "]");
lstbxFtpState.TopIndex = lstbxFtpState.Items.Count - 1;
return response;
}
catch(WebException ex)
{
lstbxFtpState.Items.Add("发送错误。返回信息为:" + ex.Status);
lstbxFtpState.TopIndex = lstbxFtpState.Items.Count - 1;
return null;
}
}

// 登录服务器事件
private void btnlogin_Click(object sender, EventArgs e)
{
if (tbxServerIp.Text == string.Empty)
{
MessageBox.Show("请先填写服务器IP地址", "提示");
return;
}

ftpUristring = "ftp://" + tbxServerIp.Text;
networkCredential = new NetworkCredential(tbxUsername.Text, tbxPassword.Text);
if (ShowFtpFileAndDirectory() == true)
{
btnlogin.Enabled = false;
btnlogout.Enabled = true;
lstbxFtpResources.Enabled = true;
lstbxFtpState.Enabled = true;
tbxServerIp.Enabled = false;
if (chkbxAnonymous.Checked == false)
{
tbxUsername.Enabled = false;
tbxPassword.Enabled = false;
chkbxAnonymous.Enabled = false;
}
else
{
chkbxAnonymous.Enabled = false;
}

tbxloginmessage.Text = "登录成功";
btnUpload.Enabled = true;
btndownload.Enabled = true;
btnDelete.Enabled = true;
}
else
{
lstbxFtpState.Enabled = true;
tbxloginmessage.Text = "登录失败";
}
}

/// <summary>
/// 设置IE代理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnProxy_Click(object sender, EventArgs e)
{
//打开注册表键
Microsoft.Win32.RegistryKey rk = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);
//设置代理可用
rk.SetValue("ProxyEnable", 1);
//设置代理IP和端口
rk.SetValue("ProxyServer",this.listBoxIP.Text);
}
/// <summary>
/// 代理IP地址
/// </summary>
/// <returns></returns>
private void Init()
{
this.listBoxIP.Items.Add("69.190.195.138:8080");

'''''''''

}