using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace textTest
{
public partial class WebForm1 : System.Web.UI.Page
{
private string downLoadFileName = "C:/Users/zuomeiyan/Desktop/DISPUTE.TXT";
//读取系统临时文件
private string savePath =System.Environment.GetEnvironmentVariable("TEMP")+"\\new.txt";
protected void Page_Load(object sender, EventArgs e)
{
ReadFromTxt();
}
protected void ReadFromTxt()
{
//读取文件
FileStream fs = new FileStream(downLoadFileName, FileMode.Open);
StreamReader sr = new StreamReader(fs, Encoding.UTF8);
//try是为了防止代码出现问题是文件流不能关闭
try
{
//新建list存放读取的数据
List<string> datalist = new List<string>();
//文件中不到末尾就一直读取
while (!sr.EndOfStream)
{
//读取每一行
string strDataOld = sr.ReadLine();
string strData = "";
//如果文件的每一行的第一个字符和最后一个字符是|,则去除
if (strDataOld[0] == '|')
{
strData = strDataOld.Substring(1, strDataOld.Length - 1);
}
if (strDataOld[strDataOld.Length - 1] == '|')
{
strData = strDataOld.Substring(1, strDataOld.Length - 2);
}
//加到list中
datalist.Add(strData);
}
var lineNo = datalist.Count;
//去除不用的行,本代码中是出去第一行第三行和最后一行
List<string> newdatalist = new List<string>();
for (int i = 1; i < lineNo - 1; i++)
{
if (i != 2)
{
newdatalist.Add(datalist[i]);
}
}
WriteToNewTxt(newdatalist);
}
catch
{
}
finally
{
//关闭文件流
sr.Close();
fs.Close();
}
}
protected void WriteToNewTxt(List<string> lst)
{
//将生成的新list写入文件
FileStream fsnew = new FileStream(savePath, FileMode.Create);
StreamWriter sw = new StreamWriter(fsnew, Encoding.UTF8);
try
{
sw.Flush();
for (int i = 0; i < lst.Count; i++)
{
sw.WriteLine(lst[i]);
}
}catch {}
finally
{
//关闭此文件
sw.Flush();
sw.Close();
fsnew.Close();
}
}
}
}