StreamWriter问题
我使用StreamReader读取一个文件中的数据,然后用Close关闭了这个流
再用StreamWriter对同一个文件进行写操作,可是发现文件内容被清空了,并且StreamWriter也没有写进任何东西!
单步调试中发现没有错误,所有该执行的语句全部执行了。
这个是什么问题呢?
[解决办法]
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace TextRWDemo
{
class Program
{
static void Main(string[] args)
{
Stream fs = new FileStream( "TextOut.txt ", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
Console.WriteLine( "Encoding type: " + sw.Encoding.ToString());
Console.WriteLine( "Format Provider: " + sw.FormatProvider.ToString());
sw.WriteLine( "Today is {0}. ", DateTime.Today.DayOfWeek);
sw.WriteLine( "Today we will mostly be using StreamWriter. ");
for (int i = 0; i < 5; i++)
sw.WriteLine( "Value {0}, its square is {1} ", i, i * i);
sw.WriteLine( "Array can be written : ");
char[] myarray = new char[] { 'a ', 'r ', 'r ', 'a ', 'y ' };
sw.Write(myarray);
sw.WriteLine( "\r\nAnd Parts of arrays can be written ");
sw.Write(myarray, 0, 3);
sw.Close();
fs.Close();
Console.WriteLine( "------------------------------------------ ");
Stream fsr = new FileStream( "TextOut.txt ", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fsr);
string data;
int line = 0;
int position = 0;
while ((data = sr.ReadLine()) != null)
{
position += data.Length;
Console.WriteLine( "Line {0} : {1} : Position = {2} : {3} ", ++line, data, position, sr.BaseStream.Position);
}
sr.BaseStream.Seek(0, SeekOrigin.Begin);
Console.WriteLine( "------------------------------------------ ");
Console.WriteLine(sr.ReadToEnd());
Console.ReadLine();
}
}
}