码迷,mamicode.com
首页 > Windows程序 > 详细

C#文件操作

时间:2015-10-14 19:51:10      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:

try
{
string directory = System.AppDomain.CurrentDomain.BaseDirectory + "logs";
string fileName = System.AppDomain.CurrentDomain.BaseDirectory + "logs\\amount.txt";

if (File.Exists(fileName))
{
//读取
StreamReader m_streamReader = new StreamReader(fileName, Encoding.GetEncoding("GB2312"), true);
m_streamReader.BaseStream.Seek(0, SeekOrigin.Begin);
int[] amount = new int[2];
string strLine;
for (int i = 0; i < 2; i++)
{
strLine = m_streamReader.ReadLine();
if (strLine != null)
{
amount[i] = Int32.Parse(strLine.Split(‘:‘)[1]);
Console.WriteLine(amount[i]);
}
}
m_streamReader.Close();
m_streamReader.Dispose();

amount[rightOrWrong]++;

//写入
FileStream fs = new FileStream(fileName, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//开始写入
sw.WriteLine("right:" + amount[0]);
sw.WriteLine("wrong:" + amount[1]);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
else
{
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
FileStream fs = new FileStream(fileName, FileMode.Create);
StreamWriter sw = new StreamWriter(fs);
//开始写入
sw.WriteLine("right:1");
sw.WriteLine("wrong:1");
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}

//Console.ReadKey();

//fs.Close();
//fs.Dispose();
}
catch (Exception ex)
{
LogHelper2.Exception(ex.Message);
throw;
}

C#文件操作

标签:

原文地址:http://www.cnblogs.com/lcyuhe/p/4878378.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!