我的txt文件的格式,文件名contact.txt
文件内容
linkman=张三
sex=男
age=30
tel=010-88888888
synopsis=这是张三的简介
张三是位好同志。
怎样读取,linkman和synopsis的值,其中linkman只有一行,但是synopsis的值可能多行,文件格式是固定,
用c#怎么取呀?
文件内容
linkman=张三
sex=男
age=30
tel=010-88888888
synopsis=这是张三的简介
张三是位好同志。
怎样读取,linkman和synopsis的值,其中linkman只有一行,但是synopsis的值可能多行,文件格式是固定,
用c#怎么取呀?
public string LinkMan;
public string Sex;
public string Age;
public string Tel;
public string Synopsis;
public override string ToString(){
return string.Format("LinkMan:{0}\nSex:{1}\nAge:{2}\nTel:{3}\nSynopsis:{4}\n"
,LinkMan,Sex,Age,Tel,Synopsis);
}
}
void Main(){
string filestring=(new StreamRead(new FileStream("contact.txt"))).ReadAll();
LinkManInfo lm=GetInfo(filestring);
Console.WriteLine(lm);
Console.Read();
}
LinkManInfo GetInfo(string input){
Regex reg=new Regex(@"linkman=(<linkman>[^\n\r]+)\r?\nsex=(<sex>[^\n\r]+)\r?\nage=(<age>[^\n\r]+)\r?\ntel=(<tel>[^\n\r]+)\r?\nsynopsis=(<synopsis>[\s\S]*)$");
Match m=reg.Match(input);
LinkMan lm = new LinManInfo();
lm.LinkMan=m.Groups["LinkMan"].Value;
lm.Sex=m.Groups["Sex"].Value;
lm.Age=m.Groups["Age"].Value;
lm.Tel=m.Groups["Tel"].Value;
lm.Synopsis=m.Groups["Synopsis"].Value;
return lm;
}
sex=男
age=30
tel=010-88888888
synopsis=这是张三的简介
张三是位好同志。
linkman=李四
sex=男
age=30
tel=010-88888888
synopsis=这是张三的简介
李四是位好同志。 他说:“
linkman=李四,是什么意思”
linkman=王二
sex=男
age=30
tel=010-88888888
synopsis=这是张三的简介
王二是位好同志。 [/code]
张三,男,30,010-88888888,这是张三的简介,这是张三的简介把前4個','看作字段閒的分割符號。後面的統統無視','就可以了。
但這樣會有個問題,就是前4個字段的内容,不可以有','(可以根據需求,用一個出現幾率最小的字符作為分割符號)其實,最好還是用XSL
char[] ch = new char[]{',','='};
tempPath = Application.StartupPath + @"\*.txt";
if (File.Exists(tempPath))
{
StreamReader sr = new StreamReader(tempPath);
try
{
while (sr.Peek() >= 0)
{
string strTemp = sr.ReadLine();
strTemp.Split(ch);
string[] strArray = strTemp.Split(ch);
}
}
}