An elegant way to consume (all bytes of a) BinaryReader?

Original Answer (Read Update Below!) Simply do: byte[] allData = read1.ReadBytes(int.MaxValue); The documentation says that it will read all bytes until the end of the stream is reached. Update Although this seems elegant, and the documentation seems to indicate that this would work, the actual implementation (checked in .NET 2, 3.5, and 4) allocates a … Read more

search text file using c# and display the line number and the complete line that contains the search keyword

This is a slight modification from: http://msdn.microsoft.com/en-us/library/aa287535%28VS.71%29.aspx int counter = 0; string line; // Read the file and display it line by line. System.IO.StreamReader file = new System.IO.StreamReader(“c:\\test.txt”); while((line = file.ReadLine()) != null) { if ( line.Contains(“word”) ) { Console.WriteLine (counter.ToString() + “: ” + line); } counter++; } file.Close();

c# – StreamReader and seeking

I realize this is really belated, but I just stumbled onto this incredible flaw in StreamReader myself; the fact that you can’t reliably seek when using StreamReader. Personally, my specific need is to have the ability to read characters, but then “back up” if a certain condition is met; it’s a side effect of one … Read more

How do I open an already opened file with a .net StreamReader?

As Jared says, You cannot do this unless the other entity which has the file open allows for shared reads. Excel allows shared reads, even for files it has open for writing. Therefore, you must open the filestream with the FileShare.ReadWrite parameter. The FileShare param is often misunderstood. It indicates what other openers of the … Read more

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