今天的学习中,收获最大的是如何从网上的页面上取到内容。具体要引用以下几个类。
using System.Net;(WebRequest 是此类的成员需要引用)
using System.IO;
using System.Text;
public string getPageInfo(string pageUrl)//读取页面代码
{
WebRequest myReq=WebRequest.Create(pageUrl);
WebResponse myRes=myReq.GetResponse();
Stream resStream=myRes.GetResponseStream();
StreamReader sr=new StreamReader(resStream,Encoding.Default);
string pageInfo=(sr.ReadToEnd()).ToString();
myRes.Close();
return pageInfo;
}
以上这就是具体的编码。
下面是如何把页面的信息存到txt中,并把txt中的内容转化为xml 相当好用值得学习
private void Page_Load(object sender, System.EventArgs e)
{
if(!this.IsPostBack)
{
Application.Lock();//防止并发
this.GetData();//获取外汇数据到TXT文件
this.txtToXml();//把TXT文件转换成XML文件
Application.UnLock();
}
}
private void GetData()//获取外汇数据到TXT文件,
{
string FilePach=Server.MapPath("data.txt");
string PageUrl="http://61.154.12.228/html/read1.txt";
StreamWriter w=File.CreateText(FilePach);
string Str=GetHtml.getPageInfo(PageUrl);
w.WriteLine(GetHtml.FormatString(Str));
w.Close();
}
private void txtToXml()//把TXT文件转换成XML文件
{
OleDbConnection conn=new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(".") + ";Extended Properties=/"Text;HDR=yes;FMT=Delimited/"");
conn.Open();
OleDbDataAdapter AdapterText=new OleDbDataAdapter("Select * from data.txt",conn);
DataSet ds=new DataSet();
AdapterText.Fill(ds,"TextFile");
XmlDataDocument objXmlDataDoc=new XmlDataDocument(ds);
objXmlDataDoc.Save(Server.MapPath("data.xml"));
}
学到东西心情就是不错。继续努力。