simultaneous read-write a file in C#

Ok, two edits later… This should work. The first time I tried it I think I had forgotten to set FileMode.Append on the oStream. string test = “foo.txt”; var oStream = new FileStream(test, FileMode.Append, FileAccess.Write, FileShare.Read); var iStream = new FileStream(test, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); var sw = new System.IO.StreamWriter(oStream); var sr = new System.IO.StreamReader(iStream); var … Read more

Should I call Close() or Dispose() for stream objects?

A quick jump into Reflector.NET shows that the Close() method on StreamWriter is: public override void Close() { this.Dispose(true); GC.SuppressFinalize(this); } And StreamReader is: public override void Close() { this.Dispose(true); } The Dispose(bool disposing) override in StreamReader is: protected override void Dispose(bool disposing) { try { if ((this.Closable && disposing) && (this.stream != null)) { … Read more

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