class WriteTextFile
{
static void Main()
{
//如果文件不存在,则创建;存在则覆盖
//该方法写入字符数组换行显示
string[] lines = { “first line”, “second line”, “third line”,“第四行” };
System.IO.File.WriteAllLines(@“C:\testDir\test.txt”, lines, Encoding.UTF8);
//如果文件不存在,则创建;存在则覆盖
string strTest = "该例子测试一个字符串写入文本文件。";
System.IO.File.WriteAllText(@"C:\testDir\test1.txt", strTest, Encoding.UTF8);
//在将文本写入文件前,处理文本行
//StreamWriter一个参数默认覆盖
//StreamWriter第二个参数为false覆盖现有文件,为true则把文本追加到文件末尾
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\testDir\test2.txt",true))
{
foreach (string line in lines)
{
if (!line.Contains("second"))
{
file.Write(line);//直接追加文件末尾,不换行
file.WriteLine(line);// 直接追加文件末尾,换行
}
}
}
}
}
class ReadTextFile
{
static void Main()
{
//直接读取出字符串
string text = System.IO.File.ReadAllText(@“C:\testDir\test1.txt”);
Console.WriteLine(text);
//按行读取为字符串数组
string[] lines = System.IO.File.ReadAllLines(@"C:\testDir\test.txt");
foreach (string line in lines)
{
Console.WriteLine(line);
}
//从头到尾以流的方式读出文本文件
//该方法会一行一行读出文本
using (System.IO.StreamReader sr = new System.IO.StreamReader(@"C:\testDir\test.txt"))
{
string str;
while ((str = sr.ReadLine()) != null)
{
Console.WriteLine(str);
}
}
Console.Read();
}
}
public static void WriteTxt(string str)
{
string path = GOIConfig.GetInstance().GetGVErrCombListTitlePath();
if (!File.Exists(path))
{
FileStream fs1 = new FileStream(path, FileMode.Create, FileAccess.Write);
//创建写入文件
StreamWriter sw = new StreamWriter(fs1);
sw.WriteLine(str);//开始写入值
sw.Close(); fs1.Close();
}
else
{
FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write);
StreamWriter sr = new StreamWriter(fs);
sr.WriteLine(str);//开始写入值
sr.Close(); fs.Close();
}
}
public static void ReadTxt(out List lstStr)
{
lstStr = new List();
string path = GOIConfig.GetInstance().GetGVErrCombListTitlePath();
if (File.Exists(path))
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(path))
{
string str;
while ((str = sr.ReadLine()) != null)
{
lstStr.Add(str);
}
}
Console.Read();
}
}
public static void UpdateTxt(string str, string path, string flag)
{
List<int> lstLine = new List<int>();
if (File.Exists(path))
{
List<string> lstFile = new List<string>();
Helper.ReadTxt(out lstFile, path);
for (int index = 0; index < lstFile.Count; index++)
{
string currStr = str.Replace(":0", "").Replace(":1", "").Replace(":2", "");
string descStr = lstFile[index].Replace(":0", "").Replace(":1", "").Replace(":2", "");
if (currStr == descStr)
{
lstLine.Add(index);
if (flag != "111")
{
WriteTxt(currStr + ":" + flag, path);
}
}
}
List<string> lines = new List<string>(File.ReadAllLines(path));
for (int i = 0; i < lstLine.Count; i++)
{
lines.RemoveAt(lstLine[i]);
}
File.WriteAllLines(path, lines.ToArray());
}
}