Home > Programming > FileStream v/s StreamReader and StreamWriter

FileStream v/s StreamReader and StreamWriter

The AppRiver dev team is studying for MSTCS 70-536. These are some observations and notes from those classes.

FileStream v/s StreamReader & StreamWriter

  1. FS supports random access.
  2. FS returns byte arrays.
  3. SR/SW use strings.
  4. If SR/SW is created with a file path instead of a stream, a FS is implicitly created.

When to use them

If you are working with textual information, use a StreamReader/Writer. Use the FileStream for binary data.

If you need to eek out the maximum performance, the FileStream, StreamReader, and StreamWriter all offer optimiztion parameters, but generally you will not need them.

  1. Ricky
    June 18, 2009 at 2:54 pm | #1

    Here’s a little something for ya .. it’ll serialize an object to xml, encrypt it, and save it as a file.


    public void SaveToFile(string Path)
    {
    byte[] data;

    using (MemoryStream ms = new MemoryStream())
    {
    XmlSerializer serializer = new XmlSerializer(typeof(List));
    serializer.Serialize(ms, this.Soldiers);

    data = ReadByteArrayFromInputStream(ms);
    ms.Close();
    }

    using (FileStream fs = File.Create(Path))
    {
    Aes aes = Aes.Create();
    using (CryptoStream cs = new CryptoStream(
    fs,
    aes.CreateEncryptor(GetKey(), GetIV()),
    CryptoStreamMode.Write))
    {
    cs.Write(data, 0, data.Length);

    cs.Close();
    }
    fs.Close();
    }
    }