首页 > Windows开发 > 详细

C# 创建读写txt

时间:2015-01-19 20:28:24      阅读:343      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!