private void btn_send_Click(object sender, EventArgs e)
{
byte[] bt = System.Text.Encoding.Default.GetBytes(this.txt_msg.Text);
TcpClient tc = new TcpClient(this.txt_tarip.Text, int.Parse(this.txt_tarport.Text));
NetworkStream nks = tc.GetStream();
nks.Write(bt, 0, bt.Length);
nks.Flush();
}
private void btn_begin_Click(object sender, EventArgs e)
{
Thread t = new Thread(Listen);
t.Start();
}
private void Listen()
{
TcpListener tl = new TcpListener(ep);
tl.Start();
while (true)
{
try
{
Socket s = tl.AcceptSocket();
byte[] bt = new byte[256];
int i = s.Receive(bt);
string msg = System.Text.Encoding.Default.GetString(bt, 0, i);
if (msg.Length != 0)
{
this.txt_accmsg.AppendText(msg + "\r\n");
}
}
catch
{ }
}
}一个用FileStream来复制文件的小程序

相比用File.Copy()方法,我觉得有两个好处
1:可以实时显示文件进度
2:当文件拷贝到一半发生异常时不会造成目标文件不可用,(用FileStream,文件可播放已拷贝部分的片段)
贴上代码:
private void button1_Click(object sender, EventArgs e)
{
FileStream fsr = null;
FileStream fsw = null;
try
{
this.progressBar1.Maximum =100;
fsr = new FileStream(this.textBox1.Text, FileMode.Open);
fsw = new FileStream(this.textBox2.Text, FileMode.Create);
byte[] bt = new byte[1024*1024];
int rcount = 0;
do
{
Application.DoEvents();
rcount = fsr.Read(bt, 0, bt.Length);
fsw.Write(bt, 0, rcount);
//this.progressBar1.Value = Convert.ToInt32(fsw.Length);
this.progressBar1.Value = ((int)(((float)fsw.Length / (float)fsr.Length)*100 )) ;
Application.DoEvents();
} while (rcount != 0);
fsr.Close();
fsw.Close();
}
catch (Exception ex)
{
if (fsr != null)
{
fsr.Close();
fsr = null;
}
if (fsw != null)
{
fsw.Close();
fsw = null;
}
MessageBox.Show(ex.ToString());
}
}