如何将流中的数据转换成中文汉字??
最近本人写了一个读取网络流,并保存为一个文本的文件,如下:功能就是输入一个网址,它将把其首页保存为一个文本文件。比方说输入了www.,就会保存为一个www.的文件。我发现保存后的文件里面中文显示不正常,是一些乱码,请高手告诉我如何正确地显示中文!!
using System;
using System.Text;
using
using
using
class app
{
static void networkstreamtest()
{
string server;
Console.WriteLine("please enter a valid URL...");
server=Console.ReadLine();
IPAddress[] hostadds;
try
{
hostadds=Dns.GetHostEntry(server).AddressList;
}
catch(Exception e)
{
Console.WriteLine(e.Message);
return;
}
Console.WriteLine(server+" ip list is:");
for(int i=0;i<hostadds.Length;i++)
{
Console.WriteLine(hostadds[i].ToString());
}
Console.WriteLine("press enter to continue...");
Console.ReadLine();
IPEndPoint ephost=new IPEndPoint(hostadds[0],80);
Socket s=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
s.Connect(ephost);
if (!s.Connected)
{
Console.WriteLine("unable to connect.");
return;
}
string str="GET / HTTP/1.1\r\nHost:"+server+"\r\nConnection: Close\r\n\r\n";
Byte[] request=Encoding.ASCII.GetBytes(str);
NetworkStream nstream=new NetworkStream(s,FileAccess.ReadWrite);
nstream.Write(request,0,request.Length);
int nextbyte;
Stream sf;
sf=new FileStream(server+".html.txt",FileMode.Create);
StreamWriter sw;
sw=new StreamWriter(sf);
while((nextbyte=nstream.ReadByte())!=-1)
{
sw.Write((char)nextbyte);
}
sw.Close();
Console.WriteLine("File"+server+".html.txt"+"is saved!");
}
public static void Main()
{
networkstreamtest();
}
}