using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Text;
using System.Threading;
/*---------------------------------------------
* 标题:(FileStream,StreamWriter,StreamReader)对文本文件的基本操作;
* 作者:靳志远(jack15850798154)
* 时间:2010-03-22
* 地点:江苏南京
* 说明 :通过 FileStream来创建文本文件 来实现对数据库的排序,获取数据前几条数据 等基本操作。
*----------------------------------------------
*/
public partial class _Default : System.Web.UI.Page
{
string line;
int counter;
int jj;
int i;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
counter = 0;
Session["counter"] = counter;
}
}
/// <summary>
///StreamWriter 文件的写入
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{
if (FileName.Text.Trim().ToString() != "")
{
string wenjianpath = Server.MapPath(this.FileName.Text.Trim());
bool b = File.Exists(Server.MapPath(this.FileName.Text.Trim()));
if (b == true)
{
//如果文件存在就直接的在数据后面接着写。不覆盖原有的数据 (FileMode.Append实现该功能。)
FileStream FS = new FileStream(wenjianpath, FileMode.Append, FileAccess.Write);
StreamWriter swrite = new StreamWriter(FS, Encoding.UTF8);
swrite.WriteLine("我是在文本文档以前有的数据中添加的。");
swrite.Close();
FS.Close();
}
else
{
//如果文件不存在就创建一个文本文件 (FileMode.Create实现该功能。)
FileStream FS = new FileStream(wenjianpath, FileMode.Create, FileAccess.Write);
StreamWriter swrite = new StreamWriter(FS, Encoding.UTF8);
swrite.WriteLine("我是创建的文本文档。");
swrite.Close(); //关闭读写流;
FS.Close(); //关闭文件流;
}
}
}
/// <summary>
///StreamReader 文件的读取
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button2_Click(object sender, EventArgs e)
{
string wenjianpath = Server.MapPath(this.FileName.Text.Trim());
StreamReader sr = new StreamReader(wenjianpath, Encoding.UTF8);
// this.TextBox1.Text = sr.ReadToEnd(); //文本内容全部读取;
this.TextBox1.Text = sr.ReadLine(); //读取文本内容的第一行内容。
}
/// <summary>
/// 每隔一秒钟就刷新一次
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Unnamed1_Tick(object sender, EventArgs e)
{
ListBox1.Items.Clear();
StreamReader sr = new StreamReader("C://aa1.txt", Encoding.UTF8);
Session["counter"] = Convert.ToInt32(Session["counter"]) + 1;
this.Label2.Text = Session["counter"].ToString();
for (int i = 0; i < Convert.ToInt32(Session["counter"].ToString()); i++)
{
if ((line=sr.ReadLine() )!= null)
{
this.ListBox1.Items.Add(line);
}
}
sr.Close();
}
}