private void MainForm_Load(object sender, System.EventArgs e)
{
tcp = new TcpClient("192.168.1.88",21);
//输入用户名
WriteNetworkStream(ref ns,"USER Anonymous");
msg.Text += ReadNetworkStream(ref ns);
//输入密码
WriteNetworkStream(ref ns,"PASS ");
msg.Text += ReadNetworkStream(ref ns);
}
private void pathBtn_Click(object sender, System.EventArgs e)
{
openPath.ShowDialog();
}
private void openPath_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
path.Text = openPath.FileName;
}
private void commBtn_Click(object sender, System.EventArgs e)
{
//刷新服务器当前目录
WriteNetworkStream(ref ns,"CWD /");
msg.Text+=ReadNetworkStream(ref ns);
//命令服务器数据模式为被动模式
WriteNetworkStream(ref ns,"PASV");
//获取服务器PASV被动模式打开的数据连接的IP和端口信息
string str = ReadNetworkStream(ref ns);
msg.Text+=str;
//请求上传文件,此处将命令转换为中文编码的字节数组以支持中文文件名
WriteNetworkStreamChs(ref ns,"STOR "+FileName(path.Text.Trim()));
//组合IP和端口
str =str.Substring(str.IndexOf("(")+1,str.IndexOf(")")-str.IndexOf("(")-1);
string ip = str.Split(',')[0]+"."+str.Split(',')[1]+"."+str.Split(',')[2]+"."+str.Split(',')[3];
int port = int.Parse(str.Split(',')[4])*256+int.Parse(str.Split(',')[5]);
//获取文件流
FileStream fs = File.OpenRead(path.Text.Trim());
//定义一个8字节数组做为缓冲区
byte[] b = new byte[8];
//建立数据传输的TCP连接
TcpClient tcp2 = new TcpClient(ip,port);
//建立该连接的网络流
NetworkStream ns2 = tcp2.GetStream();
//每8字节读取文件流中数据到网络流中,并写入到基础存储设备,采用这个方式避免了由于一次性读取大数据量到内存中造成客户机内存使用过量。
while(fs.Read(b,0,b.Length)>0)
{
//建立数据的TCP连接并将文件流的内容写入到网络流
ns2.Write(b,0,b.Length);
ns2.Flush();
}
//关闭所用的连接
fs.Close();
ns2.Close();
tcp2.Close();
msg.Text += ReadNetworkStream(ref ns);
msg.Text += ReadNetworkStream(ref ns);
}
#region //功能函数和方法
///<summary>
/// ASCII编码的命令请求
///</summary>
///<param name="ns">命令传输网络流</param>
///<param name="comm">命令字符串</param>
///<returns></returns>
protected string WriteNetworkStream(ref NetworkStream ns,string comm)
{
ns = tcp.GetStream();
byte[] b = new byte[1024];
b = System.Text.Encoding.ASCII.GetBytes(comm+"\r\n");
ns.Write(b,0,b.Length);
ns.Flush();
return string.Empty;
}
///<summary>
///中文编码方式的命令请求
///</summary>
///<param name="ns">命令传输网络流</param>
///<param name="comm">命令字符串</param>
///<returns></returns>
protected string WriteNetworkStreamChs(ref NetworkStream ns,string comm)
{
ns = tcp.GetStream();
byte[] b = new byte[1024];
//将命令以中文编码,以支持中文命令参数
b = System.Text.Encoding.GetEncoding("GB2312").GetBytes(comm+"\r\n");
ns.Write(b,0,b.Length);
ns.Flush();
return string.Empty;
}
///<summary>
///获取服务器相应字符串
///</summary>
///<param name="ns">命令传输网络流</param>
///<returns>服务器相应字符串</returns>
protected string ReadNetworkStream(ref NetworkStream ns)
{
ns = tcp.GetStream();
byte[] b = new byte[1024];
ns.Read(b,0,b.Length);
ns.Flush();
return System.Text.Encoding.ASCII.GetString(b);
}
///<summary>
///获取所选文件路径的文件名
///</summary>
///<param name="path">文件路径</param>
///<returns>文件名</returns>
protected string FileName(string path)
{
return path.Substring(path.LastIndexOf("\\")+1);
}
#endregion
}
}
查看本文来源