日期:2014-05-20  浏览次数:20746 次

C#传输文件夹中的文件到服务器 出问题了 麻烦高手救命~~~在线等
服务器短接受文件:
{
IPAddress   ip   =   IPAddress.Parse( "127.0.0.1 ");
TcpListener   listen   =   new   TcpListener(ip   ,8888);
listen.Start();
while(true)
{
this.label1.Text= "等待客户端连接............ ";
TcpClient   client   =   listen.AcceptTcpClient();
NetworkStream   ns   =   client.GetStream();

byte[]   b   =   new   byte[255];
ns.Read(b,0,b.Length);
string[]   s   =   Encoding.UTF8.GetString(b).Split( '\n ');

long   fileLength   =   long.Parse(s[1]);

byte[]   fileContent   =   new   byte[fileLength];
ns.Read(fileContent,0,(int)fileLength);

FileStream   f   =   new   FileStream( "C:\\ "   +   s[0].Substring(s[0].LastIndexOf( "\\ ")),FileMode.Create,FileAccess.Write);
f.Write(fileContent,0,(int)fileLength);
f.Close();
client.Close();
this.label1.Text= "接受文件成功! ";
}
}

客户端:
public       void       FindFile(string       dir)                                                       //参数为指定的目录      
{              
//在指定目录及子目录下查找文件,在listBox1中列出子目录及文件      
DirectoryInfo       Dir=new       DirectoryInfo(dir);      
try      
{      
foreach(DirectoryInfo       d       in       Dir.GetDirectories())           //查找子目录          
{      
FindFile(Dir+d.ToString()+ "\\ ");      
// listBox1.Items.Add(Dir+d.ToString()+ "\\ ");               //listBox1中填加目录名      
}      
foreach(FileInfo       f       in       Dir.GetFiles( "*.* "))                           //查找文件      
{      
listBox1.Items.Add(Dir+f.ToString());           //listBox1中填加文件名    
 
string   ip=this.IP.Text.Trim();
string   s=Dir+f.ToString();
TcpClient   client   =   new   TcpClient(this.IP.Text.Trim(),8888);
NetworkStream   ns   =   client.GetStream();
this.label3.Text= "已连接到服务器,准备发送文件! ";

FileInfo   f1=new   FileInfo(s);
if(f.Exists)  
{
long   l   =   f1.Length;
string   fInfo   =   s   +   "\n "   +   l;
byte[]   b   =   Encoding.UTF8.GetBytes(fInfo);
ns.Write(b,   0,   b.Length);
ns.Flush();
this.label3.Text= "正在发送文件....... ";
FileStream   fs   =   new   FileStream(s,   FileMode.Open,   FileAccess.Read);
byte[]   fBytes   =   new   byte[l];
fs.Read(fBytes,   0,   fBytes.Length);
ns.Write(fBytes,   0,   fBytes.Length);