我學習HTTP,並決定使用TcpClient從互聯網下載文件。從HTTP服務器通過TcpClient下載文件
private void requireBtn_Click(object sender, EventArgs e) {
var client = new TcpClient(addressBox.Text, 80);
var networkStream = client.GetStream();
var sWriter = new StreamWriter(networkStream, Encoding.Default);
foreach (string querLine in queryBox.Lines) {
sWriter.WriteLine(querLine);
}
sWriter.WriteLine();
sWriter.Flush();
string responceText = "";
var sReader = new StreamReader(networkStream);
string respLine;
while ((respLine = sReader.ReadLine()).Length > 0) {
responceText += respLine + "\r\n";
}
responceBox.Text = responceText;
Regex reContentLength = new Regex(@"(?<=Content-Length:\s)\d+", RegexOptions.IgnoreCase);
Int32 contentLength = Int32.Parse(reContentLength.Match(responceText).Value);
this.Text = contentLength.ToString();
if (networkStream.CanRead) {
var fileStream = new FileStream(@"C:\img.png", FileMode.Create);
byte[] buffer = new byte[1024];
int numberOfBytesRead = 0;
do {
numberOfBytesRead = networkStream.Read(buffer, 0, buffer.Length);
fileStream.Write(buffer, 0, numberOfBytesRead);
}
while (networkStream.DataAvailable);
fileStream.Flush();
fileStream.Close();
MessageBox.Show("Done!");
}
else
MessageBox.Show("Fail!");
client.Close();
}
但下載的文件已損壞。我不明白爲什麼... Source file