There are two C# projects: one project is for the client, the other one is for the server. First step is to run the server , then to choose a target folder, after that to run the client project, to choose some text.txt to send to the server's target folder. Only client can send files to the server
Demo:
1.choosing file target 2.client sends
+------------+
| tar folder | <---------------- text.txt
+------------+
My problem: there isn't compile errors or syntax errors in both projects, the only problem is that the server doesn't receives the .txt file.
Client:
First I designed a form for the client such as:
And placed an OpenFileDialog from the ToolBox-> Dialogs-> OpenFileDialog control.
Full code:
namespace SFileTransfer
{
public partial class Form1 : Form
{
string n;
byte[] b1;
OpenFileDialog op;
private void button1_Click(object sender, EventArgs e) //browse btn
{
op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
{
string t = textBox1.Text;
t = op.FileName;
FileInfo fi = new FileInfo(textBox1.Text = op.FileName);
n = fi.Name + "." + fi.Length;
TcpClient client = new TcpClient("127.0.0.1", 8100);//"127.0.0.1", 5055
StreamWriter sw = new StreamWriter(client.GetStream());
sw.WriteLine(n);
sw.Flush();
// label2.Text = "File Transferred....";
}
}
private void button2_Click(object sender, EventArgs e) //send btn
{
TcpClient client = new TcpClient("127.0.0.1", 8100);//5050
Stream s = client.GetStream();
b1 = File.ReadAllBytes(op.FileName);
s.Write(b1, 0, b1.Length);
client.Close();
// label2.Text = "File Transferred....";
}
}
}
Server:
Created and designed a Form for Server like:
Then Placed a folderBrowserDialog from the ToolBox->Dialogs-> folderBrowserDialog.
Full code:
namespace SFileTransferServer
{
public partial class Form1 : Form
{
string rd;
byte[] b1;
string v;
int m=1;
TcpListener list;
TcpClient client;
Int32 port = 8100;//5050
Int32 port1 = 8100;//5055
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
private void button1_Click(object sender, EventArgs e) //browse button
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
list = new TcpListener(localAddr, port1);
list.Start();
client = list.AcceptTcpClient();
MessageBox.Show("ggggggg" + m.ToString());
Stream s = client.GetStream();
b1 = new byte[m];
s.Read(b1, 0, b1.Length);
MessageBox.Show(textBox1.Text);
File.WriteAllBytes(textBox1.Text+ "\\" + rd.Substring(0, rd.LastIndexOf('.')), b1);
list.Stop();
client.Close();
label1.Text = "File Received......";
}
}
private void Form2_Load(object sender, EventArgs e)
{
TcpListener list = new TcpListener(localAddr, port);
list.Start();
TcpClient client = list.AcceptTcpClient();
MessageBox.Show("Client trying to connect");
StreamReader sr = new StreamReader(client.GetStream());
rd = sr.ReadLine();
v = rd.Substring(rd.LastIndexOf('.') + 1);
m = int.Parse(v);
list.Stop();
client.Close();
}
}
}
Based on this page