
C#TXT文档操作问题
最后要可以根据集合(或字典)重写TXT文档,要代码。 展开
StringBuilder sb = new StringBuilder();
//读取
string[] strs= File.ReadAllLines(@"D:\Users\AdminGD\Desktop\百度.txt", Encoding.Default);
for (int i = 0; i <strs.Length ; i++)
{ //分割字符串
string[] strarry = strs[i].Split(new char[]{'|'}, StringSplitOptions.RemoveEmptyEntries);
//拼接
sb.Append(string.Join("|", strarry));
//换行
sb.Append('\r');
}
//写入
File.WriteAllText(@"D:\Users\AdminGD\Desktop\百度度.txt", sb.ToString());
下面是代码,参考一下,另有附件:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ReadTxtDemo
{
class Program
{
public static List<Person> ReadPerson(string file)
{
List<Person> persons = null;
using (StreamReader sr = File.OpenText(file)) {
persons = new List<Person>();
while(!sr.EndOfStream) {
string line = sr.ReadLine();
//如果是空行,读取下一行
if (string.IsNullOrEmpty(line)) {
continue;
}
string[] items = line.Split('|');
persons.Add(new Person(items[0], items[1], items[2], items[3]));
}
}
return persons;
}
public static void WritePerson(string file, List<Person> persons)
{
using (StreamWriter sw = File.CreateText(file)) {
foreach (Person person in persons) {
sw.WriteLine("{0}|{1}|{2}|{3}", person.Name, person.Profession, person.Country, person.Address);
}
}
}
static void Main(string[] args)
{
//读取数据
List<Person> persons = ReadPerson("person.txt");
//显示
foreach (Person person in persons) {
Console.WriteLine("{0}\t{1}\t{2}\t{3}", person.Name, person.Profession, person.Country, person.Address);
}
//删除第一行数据
persons.RemoveAt(0);
//添加一行数据
persons.Add(new Person("赵五", "程序员", "中国", "深圳"));
//保存
WritePerson("person.txt", persons);
Console.ReadKey();
}
}
class Person
{
public string Name { get; set; }
public string Profession { get; set; }
public string Country { get; set; }
public string Address { get; set; }
public Person(string name = "", string profession = "", string country = "", string address = "")
{
this.Name = name;
this.Profession = profession;
this.Country = country;
this.Address = address;
}
}
}
数组=字符串.Split('|');
2013-06-16