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

C# 创建读写txt

时间:2015-01-19 20:31:22      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

   try
   {
        string filePath = Application.StartupPath + "tst.txt";
        FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None);
        StreamWriter sw = new StreamWriter(fs);   
        sw.WriteLine("");
        sw.Flush();
        sw.Close();
        fs.Close();
   }
   catch(IOException ioEx) 
   {
         Logger.Error("写入txt失败:" + ioEx.ToString());
   }

FileMOde.Append:文件不存在的话创建文件,存在的话打开文件,流指向文件的末尾,只能与枚举FileAccess.Write联合使用。

string filePath = Application.StartupPath + "l.txt";
try
{                
       FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
       StreamWriter sw = new StreamWriter(fs);
       sw.BaseStream.Seek(0, SeekOrigin.End);
       sw.Write("test");
       sw.Flush();
       sw.Close();
       fs.Close();
}
catch(IOException ioEx) 
{
       Logger.Error("写入txt失败:" + ioEx.ToString());
}

 

 FileMode.OpenOrCreate: 文件不存在的话创建文件,存在则打开文件,流指向文件的开头。如果追加文本,可设置SeekOrigin.End。

string filePath = Application.StartupPath + "l.txt";
try
{
       FileInfo finfo = new FileInfo(filePath);
       using (FileStream fs = finfo.OpenWrite())
       {
             StreamWriter sw = new StreamWriter(fs);
             sw.BaseStream.Seek(0, SeekOrigin.End);
             sw.Write("test");
             sw.Flush();
             sw.Close();
             fs.Close();
        }
}
catch(IOExcepton ioEx)
{
       Logger.Error("写入txt失败:" + ioEx.ToString());
}

 

FileInfo提供了OpenRed()、OpenWrite()方法创建FileStream对象,打开只读、只写文件。
读取txt用到StreaReader,此处不多记录:

StreamReader sr = new StreamReader(filePath);

string strRead;
while((strRead=sr.ReadLine())!=null)

{

     sbResult.Appen(strRead);

}

sr.Close();

 

C# 创建读写txt

标签:

原文地址:http://www.cnblogs.com/yingyi/p/4234480.html

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