C# 怎么样删除 文本中 的 一点内容,比如 现在有个文本是
F:\11.txt.
内容: 张三|软件学院|1439同学
张四|软件学院|1439同学
张五|软件学院|1439同学
现在 要删除 张四|软件学院|1439同学
我大概知道怎么做 ,就是 对文本内容 进行扫描,把扫描的内容 使用ArrartLis类 ,添加
到数组里,再进行 删除, 再又进行重写,
代码 这可怎么写??
给你一段我手写的代码:
private void DeleteTxt(string filePath, string modifyName)
{
List<string> listContent = new List<string>();
try
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
{
StreamReader sr = new StreamReader(fs, Encoding.Unicode);
while (!sr.EndOfStream)
{
string strLine = sr.ReadLine();
if (!strLine.Contains(modifyName))
{
listContent.Add(strLine);
}
}
sr.Close();
}
using (FileStream fs = new FileStream(filePath, FileMode.Truncate, FileAccess.ReadWrite))
{
StreamWriter sw = new StreamWriter(fs, Encoding.Unicode);
foreach (string strline in listContent)
{
sw.WriteLine(strline);
}
sw.Flush();
sw.Close();
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
注意上面的你的11.txt一定要保存为unicode格式的文件。否则你读取的就是乱码喽!!!!!
强烈建议用List而不是用ArrayList
这涉及一个装箱和封箱的问题,总而言之就是ArrayList的性能不是很好,并且ArrayList有的功能List都有
然后回归问题
命名空间加一个 using System.IO;
然后用string[] s1 = file.ReadAllString("F:\11.txt");
一定要用string[]以及ReadAllString
这样才是按行的读并按行存到字符串数组s里
这样存进去之后
List s2 = new List();
s2=s1.toList();
s2[1]即文本的第二行就是你要删的
直接做s2.removeat(1);
然后把s2再转成string数组
string s3 = s2.toArray();
把s3写入文件就行
file.WriteAllstring("F:\11.txt",s3);
没那么麻烦:
string[] lines = File.ReadAllLines("f:\\11.txt");
var result = lines.Where(x => x != "张四|软件学院|1439同学");
File.WriteAllLines("f:\\11.txt", result);
再多教你一些
删除全部李四的记录:
string[] lines = File.ReadAllLines("f:\\11.txt");
var result = lines.Where(x => x。Split('|')[0] != "李四");
File.WriteAllLines("f:\\11.txt", result);
干嘛不存数据库里面?
不行直接File读出所有内容直接replace下再写回
导入下面2个类
using System.Text;
using System.IO;
/// <summary>
///
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="str">要删除的内容</param>
/// <param name="encoding">文件编码</param>
public void DelStr(string path, string str,Encoding encoding)
{
string s = File.ReadAllText(path, encoding);
s = s.Replace(str, "");
File.WriteAllText(path, s, encoding);
}
protected void Page_Load(object sender, EventArgs e)
{
DelStr("F:\\11.txt","张四|软件学院|1439同学",Encoding.GetEncoding(936));//注意编码,如果是utf-8最后一个要改为Encoding.UTF8,要不会乱码
}
再多教你一些
删除全部李四的记录:
string[] lines = File.ReadAllLines("f:\\11.txt");
var result = lines.Where(x => x.Split('|')[0] != "李四");
File.WriteAllLines("f:\\11.txt", result);
注意哦,使用这些代码,先要加上
using System.IO;