1

後のコードのように、fileStream を 2 回作成したくないので、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();
            }
        }
    }
}
4

1 に答える 1