当我尝试使用由同一个fileStream构造的StreamReader时,Stream是不可写的?

时间:2015-03-10 13:33:36

标签: filestream streamwriter writable

作为代码之后,我不想创建fileStream两次,所以我在fileStream中编写streamWriter。但是,当尝试实例化StreamWriter时,代码抛出异常是如此奇怪。我猜fs的读指针到达最后,但这只是猜测。我想知道为什么遇到这个错误。请帮帮我!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Stream
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = "E:\\test.txt";
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                using (StreamReader r = new StreamReader(fs)) {

                }

                using (StreamWriter w = new StreamWriter(fs)) {
                    //exception when new StreamWriter(fs)
                    //stream is not writable.  why? why? why?
                }

                Console.ReadKey();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

完成使用(StreamReader r = new StreamReader(fs))后,代码将自动调用fs的close()。因此,当接下来使用fs时,会检查StreamWriter的构造函数:if(steam == null){throw new ArgumentException(" stream is not writable")}。它就在那里!