Does disposing streamreader close the stream?

Yes, StreamReader, StreamWriter, BinaryReader and BinaryWriter all close/dispose their underlying streams when you call Dispose on them. They don’t dispose of the stream if the reader/writer is just garbage collected though – you should always dispose of the reader/writer, preferrably with a using statement. (In fact, none of these classes have finalizers, nor should they … Read more

Reading large text files with streams in C#

You can improve read speed by using a BufferedStream, like this: using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (BufferedStream bs = new BufferedStream(fs)) using (StreamReader sr = new StreamReader(bs)) { string line; while ((line = sr.ReadLine()) != null) { } } March 2013 UPDATE I recently wrote code for reading and processing (searching … Read more

Memory Leak using StreamReader and XmlSerializer

The leak is here: new XmlSerializer(typeof(XMLObj), new XmlRootAttribute(“rootNode”)) XmlSerializer uses assembly generation, and assemblies cannot be collected. It does some automatic cache/reuse for the simplest constructor scenarios (new XmlSerializer(Type), etc), but not for this scenario. Consequently, you should cache it manually: static readonly XmlSerializer mySerializer = new XmlSerializer(typeof(XMLObj), new XmlRootAttribute(“rootNode”)) and use the cached serializer … Read more

How to read embedded resource text file

You can use the Assembly.GetManifestResourceStream Method: Add the following usings using System.IO; using System.Reflection; Set property of relevant file: Parameter Build Action with value Embedded Resource Use the following code var assembly = Assembly.GetExecutingAssembly(); var resourceName = “MyCompany.MyProduct.MyFile.txt”; using (Stream stream = assembly.GetManifestResourceStream(resourceName)) using (StreamReader reader = new StreamReader(stream)) { string result = reader.ReadToEnd(); } … Read more