.net 读取文件数据
//新建一个data.txt 内容如下 169.868592016381,-73.2891742320069 169.388181055691,-73.5364222712322 169.750305089806,-73.6008442380541 169.918029151954,-73.5541793331424 169.868592016381,-73.2891742320069 END 166.631652045891,-77.1728092143666 166.372218060531,-77.2768852946332 166.61984412359,-77.3842371903049 166.217103062991,-77.5354373361399 166.858577993192,-77.6655682271997 166.557771101318,-77.7088312528823 166.873689055903,-77.7293783150887 166.776642039652,-77.8577902454421 167.583618151274,-77.6366872062885 168.940557082799,-77.6402872337091 169.423001996118,-77.4629782976242 167.379696002005,-77.3836162589165 166.631652045891,-77.1728092143666 END
//创建一个类,用来分析与处理文本文件内的数据。 public class XY { public double X; public double Y; public XY(double x,double y) { this.X = x; this.Y = y; } public static bool TryParse(string line,out XY xy) { xy = null; if (string.IsNullOrEmpty(line)) return false; string[] array = line.Trim().Split(','); if (array.Length != 2) return false; double a; if (!double.TryParse(array[0].ToString(), out a)) return false; double b; if (!double.TryParse(array[1].ToString(), out b)) return false; xy = new XY(a, b); return true; } public override string ToString() { return string.Format("{0}{1}",X,Y); } }
//在程序中,应用上面写好的类XY: public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string txt = Server.MapPath("~/data.txt"); var txtLines = System.IO.File.ReadAllLines(txt); var o = new List<XY>(); foreach (string line in txtLines) { XY xy; if (XY.TryParse(line,out xy)) { o.Add(xy); } } o.ForEach(delegate(XY xy) { Response.Write(xy.ToString() + "<br/>"); }); } }
//数据全部收集于List<XY>泛型集合中。但在上图中,Insus.NET有输出至网页上。
//创建实例,读取XML XmlDocument xmldoc = new XmlDocument(); string path = HttpContext.Current.Server.MapPath("../XMLFile/ChatInfor.xml"); xmldoc.Load(path); //查找根节点 XmlNode chat = xmldoc.SelectSingleNode("Chat"); //创建节点 XmlElement infor = xmldoc.CreateElement("infor"); //设置属性 infor.SetAttribute("id", mid); XmlElement xuser = xmldoc.CreateElement("userid"); //插入文本 xuser.InnerText = uid; infor.AppendChild(xuser); XmlElement xdate = xmldoc.CreateElement("date"); xdate.InnerText = date; infor.AppendChild(xdate); XmlElement xmess = xmldoc.CreateElement("content"); xmess.InnerText = mess; infor.AppendChild(xmess); //存入根节点,保存文件 chat.AppendChild(infor); xmldoc.Save(path);