using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace TestFile
{
class MyFile
{
public Boolean checkFile(string path)
{
if (System.IO.File.Exists(@path))
{
Console.WriteLine("文件存在");
return true;
}
else
{
Console.WriteLine("文件不存在..");
System.IO.File.Create(path);
return false;
}
}
public void writeAfter(string path, string line)
{
StreamWriter rw = File.AppendText(path);
rw.WriteLine(line);
rw.Flush();
rw.Close();
}
public List<string> searchById(string path, string id)
{
List<string> lines = new List<string>();
FileStream fileStream = null;
StreamReader streamReader = null;
try
{
fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
streamReader = new StreamReader(fileStream, Encoding.Default);
string content = streamReader.ReadLine();
while (content != null)
{
if(content.StartsWith(id)){
lines.Add(content);
}
content = streamReader.ReadLine();
}
if (lines.Capacity == 0) {
lines.Add("nothing was found");
}
}
catch
{
}
finally
{
if (fileStream != null)
{
fileStream.Close();
}
if (streamReader != null)
{
streamReader.Close();
}
}
return lines;
}
//删除某一行
public void deleteOne(string path,string id)
{
List<string> lines = new List<string>(File.ReadAllLines(path, Encoding.GetEncoding(936)));
List<string> results =new List<string>();
foreach (string line in lines)
{
if (!line.StartsWith(id)) {
results.Add(line);//这里必须是另一个List 不能对同一个list即删除又遍历的
//Console.WriteLine(line + " del");
}
}
File.WriteAllLines(path, results.ToArray(), Encoding.GetEncoding(936));
}
}
}