📄 transferstuff.cs
字号:
case "04":
responseData.errorType = HttpErrorType.NotFound;
break;
case "03":
responseData.errorType = HttpErrorType.Forbidden;
break;
case "01":
responseData.errorType= HttpErrorType.AuthRequired;
break;
default:
responseData.errorType = HttpErrorType.MiscClientErr;
break;
}
break;
case "5":
responseData.errorType = HttpErrorType.MiscServerErr;
break;
}
}
else {
tempstring = splitbyline[i].Split(new char[] {':'});
switch (tempstring[0].ToLower().Trim()) {
case "content-length":
responseData.contentLength=Int32.Parse(tempstring[1].Trim());
break;
case "www-authenticate":
responseData.WwwAuthenticate=tempstring[1].Trim();
break;
case "location":
responseData.Location=tempstring[1].Trim();
break;
}
}
}
return responseData;
}
public void KillMe() {
if (connection.Connected) {
connection.Shutdown(SocketShutdown.Both);
connection.Close();
}
ns.Close();
br.Close();
}
~HttpFunctions() {
KillMe();
}
}
public enum CmdState {
NewConn,
SentUser,
SentPwd,
ChangedDir,
SentPort,
RequestedFile,
ChangedType,
SentSize,
SentRest
}
// FTP transfer stuff
public class FtpFunctions {
public Socket dataconn;
public NetworkStream ns;
public BinaryReader br;
protected Socket commandconn;
protected UrlProperties urlProperties;
protected CmdState cmdstate=CmdState.NewConn;
protected bool quitloop=false;
protected TcpListener dplisten;
protected long filesize = 0;
protected long startfrom = 0;
public long GetUrl(UrlProperties urlProperties, long startfrom) {
this.urlProperties = urlProperties;
this.startfrom = startfrom;
commandconn = new Socket(0, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ep = new IPEndPoint(Dns.Resolve(urlProperties.hostName).AddressList[0], urlProperties.portNo);
commandconn.Connect(ep);
int bytesreceived=1;
byte[] received = new byte[512];
string wholeresp = null;
while (bytesreceived > 0 && !quitloop) {
bytesreceived = commandconn.Receive(received, 0, received.Length, 0);
wholeresp = wholeresp + Encoding.ASCII.GetString(received, 0, bytesreceived);
if (wholeresp.Length > 2 && wholeresp.Substring(wholeresp.Length-2, 2) == "\r\n") { // a CrLf pair means that we've hit the end of a response
processresponse(wholeresp);
wholeresp=null;
}
}
return filesize;
}
protected void processresponse(string response) {
string[] splitup = response.Substring(0,response.Length-2).Split(" ".ToCharArray());
int responsecode = Int32.Parse(splitup[0]);
switch (cmdstate) {
case CmdState.NewConn:
switch (responsecode) {
case 120: // unavailable for the moment
throw new Exception("FTP Server currently unavailable. Try again later.");
case 220: // success, send off the username
if (urlProperties.ftpusername == null && urlProperties.ftppwd == null) {
AuthForm af = new AuthForm(true);
DialogResult dlg = af.ShowDialog();
if (dlg == DialogResult.OK) {
urlProperties.ftpusername = af.username;
urlProperties.ftppwd = af.password;
}
else throw new Exception("You must provide authentication details");
}
SendData("USER " + (urlProperties.ftpusername != "" ? urlProperties.ftpusername : "Anonymous") + "\r\n");
cmdstate = CmdState.SentUser;
break;
case 421: // server is dead
throw new Exception("Service not available, closing connection.");
}
break;
case CmdState.SentUser:
switch (responsecode) {
case 331: // they want a password
SendData("PASS " + (urlProperties.ftppwd!= "" ? urlProperties.ftppwd : "foo@nowhere.com") + "\r\n");
cmdstate = CmdState.SentPwd;
break;
case 230: // we're in
SendData("CWD " + getpath(urlProperties.docPath) + "\r\n");
cmdstate = CmdState.ChangedDir;
break;
default:
throw new Exception("Error logging in. Check your login details.");
}
break;
case CmdState.SentPwd:
switch (responsecode) {
case 230: // kewl
SendData("CWD " + getpath(urlProperties.docPath) + "\r\n");
cmdstate = CmdState.ChangedDir;
break;
default:
throw new Exception("Error logging in. Check your login details.");
}
break;
case CmdState.ChangedDir:
switch (responsecode) {
case 250: // success
opendataconn();
cmdstate = CmdState.SentPort;
break;
default:
throw new Exception("Remote path not found/access denied.");
}
break;
case CmdState.SentPort:
switch (responsecode) {
case 200:
SendData("TYPE I\r\n");
cmdstate=CmdState.ChangedType;
break;
default:
throw new Exception("PORT command failed");
}
break;
case CmdState.ChangedType:
SendData("REST " + startfrom + "\r\n");
cmdstate = CmdState.SentRest;
break;
case CmdState.SentRest:
switch (responsecode) {
case 350: // cool, resuming's supported
SendData("SIZE " + urlProperties.fileName + "\r\n");
cmdstate = CmdState.SentSize;
break;
default: // need to somehow tell the download function that we can't resume
break;
}
break;
case CmdState.SentSize:
switch (responsecode) {
case 213:
filesize = Int32.Parse(splitup[1]);
SendData("RETR " + urlProperties.fileName + "\r\n");
cmdstate = CmdState.RequestedFile;
break;
default: // SIZE command isn't implemented or file couldn't be found.
break;
}
break;
case CmdState.RequestedFile:
switch (responsecode) {
case 125:
case 150:
while (dataconn==null) {
dataconn=dplisten.AcceptSocket();
}
ns=new NetworkStream(dataconn);
br=new BinaryReader(ns);
quitloop=true;
break;
case 450:
case 421:
case 550:
case 500:
case 501:
case 530:
throw new Exception("Error accessing requested file");
}
break;
}
}
protected void SendData(string data) {
byte[] bytedata;
bytedata = Encoding.ASCII.GetBytes(data);
commandconn.Send(bytedata, bytedata.Length, 0);
}
protected void opendataconn() {
dplisten = new TcpListener(((IPEndPoint)commandconn.LocalEndPoint).Address, 0);
dplisten.Start();
string[] splitipaddr = ((IPEndPoint)dplisten.LocalEndpoint).Address.ToString().Split(".".ToCharArray());
int portno=((IPEndPoint)dplisten.LocalEndpoint).Port;
SendData("PORT " + splitipaddr[0] + "," + splitipaddr[1] + "," + splitipaddr[2] + "," + splitipaddr[3] + "," + (portno / 256) + "," + (portno % 256) + "\r\n");
}
protected string getpath(string path) {
int i=path.Length-1;
while (i != 0 && path.Substring(i, 1) != "/") i--;
if (path.Substring(i, 1)=="/") {
return path.Substring(0, path.Length-i-1);
}
else
return null;
}
public void KillMe() {
if (dataconn.Connected) {
dataconn.Shutdown(SocketShutdown.Both);
dataconn.Close();
}
SendData("QUIT\r\n");
if (commandconn.Connected) {
commandconn.Shutdown(SocketShutdown.Both);
commandconn.Close();
}
ns.Close();
br.Close();
}
// destructor
~FtpFunctions() {
KillMe();
}
}
public class AuthForm : Form {
Label explanationLabel = new Label();
Label usernameLabel = new Label();
TextBox usernameTextBox = new TextBox();
Label passwordLabel = new Label();
TextBox passwordTextBox = new TextBox();
Button okButton = new Button();
Button cancelButton = new Button();
CheckBox anonCheckbox = new CheckBox();
public string username=null;
public string password=null;
public bool isanon=false;
public AuthForm(bool isftp) {
this.Size = new Size(300, 180);
this.FormBorderStyle = FormBorderStyle.FixedDialog;
this.MaximizeBox=false;
this.MinimizeBox=false;
this.Text = "Just stop right there a minute, pal ...";
this.AcceptButton = okButton;
this.CancelButton = cancelButton;
explanationLabel.Location = new Point(15, 10);
explanationLabel.Size = new Size(270, 40);
explanationLabel.Text = "Authentication is required to access this resource. Please supply your user name and password in the fields below:";
usernameLabel.Location = new Point(25, 60);
usernameLabel.Text = "User name:";
usernameLabel.AutoSize = true;
usernameTextBox.Location = new Point(100, 56);
usernameTextBox.Size = new Size(160, 20);
passwordLabel.Location = new Point(25, 83);
passwordLabel.Text = "Password:";
passwordLabel.AutoSize = true;
passwordTextBox.Location = new Point(100, 79);
passwordTextBox.Size = new Size(160, 20);
passwordTextBox.PasswordChar = '*';
anonCheckbox.Location = new Point(100, 103);
anonCheckbox.Size = new Size(160, 15);
anonCheckbox.Text = "Anonymous";
anonCheckbox.Click += new EventHandler(anonCheckbox_Click);
if (!isftp) anonCheckbox.Visible=false;
okButton.Location = new Point(103, 120);
okButton.Text = "&OK";
okButton.DialogResult = DialogResult.OK;
okButton.Click += new EventHandler(okButton_Click);
cancelButton.Location = new Point(184, 120);
cancelButton.Text = "&Cancel";
cancelButton.DialogResult = DialogResult.Cancel;
cancelButton.Click += new EventHandler(cancelButton_Click);
this.Controls.Add(explanationLabel);
this.Controls.Add(usernameLabel);
this.Controls.Add(usernameTextBox);
this.Controls.Add(passwordLabel);
this.Controls.Add(passwordTextBox);
this.Controls.Add(anonCheckbox);
this.Controls.Add(okButton);
this.Controls.Add(cancelButton);
}
void okButton_Click(Object Src, EventArgs e) {
username=usernameTextBox.Text;
password=passwordTextBox.Text;
isanon=anonCheckbox.Checked;
return;
}
void cancelButton_Click(Object Src, EventArgs e) {
return;
}
void anonCheckbox_Click(Object Src, EventArgs e) {
if (anonCheckbox.Checked) {
passwordTextBox.PasswordChar = '\0';
if (usernameTextBox.Text == "") usernameTextBox.Text = "Anonymous";
}
else {
passwordTextBox.PasswordChar = '*';
}
return;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -