StreamReader和StreamWriter已经可以实现文件读写,为什么还要使用FileStream?

解决方案 »

  1.   

    1、StreamReader只用来读字符串。
    2、StreamReader可以用来读任何Stream,包括FileStream也包括NetworkStream,MemoryStream等等。3、FileStream用来操作文件流。可读写,可字符串,也可二进制。重要的区别是,StreamReader是读者,用来读任何输入流;FileStream是文件流,可以被读,被写。
      

  2.   

    比如说看看 StreamWriter源代码public StreamWriter(string path) : this(path, false, StreamWriter.UTF8NoBOM, 1024)
    {
    }public StreamWriter(string path, bool append, Encoding encoding, int bufferSize) : this(path, append, encoding, bufferSize, true)
    {
    }internal StreamWriter(string path, bool append, Encoding encoding, int bufferSize, bool checkHost) : base(null)
    {
    if (path == null)
    {
    throw new ArgumentNullException("path");
    }
    if (encoding == null)
    {
    throw new ArgumentNullException("encoding");
    }
    if (path.Length == 0)
    {
    throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
    }
    if (bufferSize <= 0)
    {
    throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
    }
    Stream streamArg = StreamWriter.CreateFile(path, append, checkHost);
    this.Init(streamArg, encoding, bufferSize, false);
    }private static Stream CreateFile(string path, bool append, bool checkHost)
    {
    FileMode mode = append ? FileMode.Append : FileMode.Create;
    return new FileStream(path, mode, FileAccess.Write, FileShare.Read, 4096, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost);
    }[SecuritySafeCritical]
    private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen)
    {
    this.stream = streamArg;
    this.encoding = encodingArg;
    this.encoder = this.encoding.GetEncoder();
    if (bufferSize < 128)
    {
    bufferSize = 128;
    }
    this.charBuffer = new char[bufferSize];
    this.byteBuffer = new byte[this.encoding.GetMaxByteCount(bufferSize)];
    this.charLen = bufferSize;
    if (this.stream.CanSeek && this.stream.Position > 0L)
    {
    this.haveWrittenPreamble = true;
    }
    this.closable = !shouldLeaveOpen;
    if (Mda.StreamWriterBufferedDataLost.Enabled)
    {
    string cs = null;
    if (Mda.StreamWriterBufferedDataLost.CaptureAllocatedCallStack)
    {
    cs = Environment.GetStackTrace(null, false);
    }
    this.mdaHelper = new StreamWriter.MdaHelper(this, cs);
    }
    }
    这就是原因!所谓原因,你要自己看。这并不是对你的过高要求,这个要求是正合适那些想在工作前就学到本领的人的。
      

  3.   

    这好比如说,苹果出了个IPhone,它不能强迫人家富士康不再给别的厂商代工代工电子产品吧。