标签:
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();
标签:
原文地址:http://www.cnblogs.com/yingyi/p/4234480.html