我已经为此工作了两天,但我无法弄清楚。我想通过 TCP 传输文件(服务器发送,客户端接收)。
我面临的问题是我想实现一种方法让接收方知道它正在获取的文件的文件名是什么。到目前为止我的工作代码
public void SendFile(string path, string IP)
{
TcpClient client = new TcpClient();
client.Connect(IP, 1095);
using (NetworkStream networkStream = client.GetStream())
using (FileStream fileStream = File.OpenRead(path))
{
ASCIIEncoding asci = new ASCIIEncoding();
byte[] b = asci.GetBytes(path);
networkStream.Write(b, 0, b.Length);
networkStream.Flush();
fileStream.CopyTo(networkStream);
}
client.Close();
}
private void ListenForFile()
{
TcpListener listener = new TcpListener(IPAddress.Any, 1095);
listener.Start();
using (TcpClient incoming = listener.AcceptTcpClient())
using (NetworkStream networkStream = incoming.GetStream())
using (FileStream fileStream = File.OpenWrite(@pathName + @"\something.extension"))
{
networkStream.CopyTo(fileStream);
}
listener.Stop();
}