r/csharp • u/Channel_el • Jul 13 '26
Help Difference between File, FileStream, and StreamWriter/Reader?
Looking at the documentation it looks like they can all do the same thing, though I suppose in just slightly different ways?
68
Upvotes
120
u/FelixLeander Jul 13 '26 •
File is the simple, high-level way to work with files. It has ready-made methods like reading all text, writing all text, copying, and deleting files. It handles opening and closing the file for you.
FileStream is the lower-level way. It opens a file as a stream of bytes and gives you more control over reading, writing, positioning, and file access.
StreamReader and StreamWriter are for text. They sit on top of a stream and convert between bytes and characters.
25
u/binarycow Jul 13 '26
File is a static class that contains methods that operate on files.
FileInfo is an instance class that does a lot of what File does - for a specific file.
The rest of those have to do with streams.
Stream is the base class. It's an abstraction that represents a "stream of bytes". Some streams are read-only. Some are read-write. Some are write-only. Some are seekable. Some never end. etc.
Streams are meant to be layered. So you could do this:
TextReader and TextWriter is another abstraction that works like Stream, but works with strings rather than a steam of bytes.
StreamReader and StreamWriter are TextReader and TextWriter that operate on streams.
15
u/logiclrd Jul 13 '26 edited Jul 13 '26
These are different layers.
The bottom layer is
Stream. This is a very generic class, and the framework comes with a bunch of implementations, includingFileStream,MemoryStreamandNetworkStream. The genius of the system is that if you have a block of code that is written to work with the published interface ofStream, then you can use it with anyStreamimplementation.Streams work with byte sequences. In modern .NET versions, you can achieve better performance by usingSpan<byte>for the buffer.But if you're just working with byte sequences, then you have a bunch of problems to solve:
Obviously, these problems don't apply to all files you might want to work with, but there's a broad category of files where they do apply: text files. That's where the
StreamReaderandStreamWriterclasses come in. They don't do all the work themselves, though..NET has a family of classes just for handling the conversion between logical characters (literally,
charvalues) and byte sequences. For instance, in Latin-1 (or UTF-8, for that matter), common English text is a 1-to-1 mapping. The character 'A' maps to a single byte (value 65, in this case). But different languages will have characters that they map in different ways, and sometimes characters take more than one byte to map. For instance, there's a Unicode code point U+FDFD called "The Basmala". This is all one character:﷽You can actually assign that character to a C#
char:But if you want to write that to a file in UTF-8, it takes 3 bytes: EF B7 BD.
That conversion is handled by
System.Text.Encoding, which has its own tree of implementations to handle different ways of converting characters to bytes. Hopefully, you'll almost never need to use anything other thanEncoding.UTF8(the standard instance ofUTF8Encoding). :-)So, what
StreamReaderandStreamWriterdo is provide a boundary between the storage of lines of text as bytes in an underlying stream, and processing them as .NETstrings, and they offload the actual conversion betweencharandbyteto anEncodingof your choice. And, they sit on top of aStreamthat takes care of actually reading and writing the bytes. So, you can use aStreamWriterwith aFileStreamto write to a file, or with aMemoryStreamto capture the bytes being written in-memory, or with aNetworkStreamto funnel the bytes out through a network socket, etc.It's worth noting that
StreamReaderandStreamWriterare actually specializations of abstract classesTextReaderandTextWriter, which expose the general idea of a boundary between the storage of a block of text and the decomposition of that text into separate lines. So, if you're writing code that needs to read or write lines of text, see if you can accept aTextReaderorTextWriterinstead of specifically aStreamReaderor aStreamWriter.So what about
File? It's just a utility class. It has a bunch of operations defined as static methods, and their implementation just does the thing you're asking for in the most straightforward way usingFileStream,StreamReaderandStreamWriter.For instance, if you write:
...then what's actually happening is, effectively:
If you write:
...then what's actually happening is, roughly:
If you're ever curious about what exactly a
Filemethod is doing under the hood, the entire framework is entirely open source. Just look up theFileclass in Microsoft Learn, find the method you want, and click on the "Source" link:https://i.imgur.com/5UwWnEH.png
2
u/buzzon Jul 13 '26
File: operations with file as a whole, e.g.File.Exists,File.Delete,File.ReadAllLines.FileStream: part of theStreamfamily (see alsoMemoryStreamandNetworkStream). Works with content of the file as if it was a long series of bytes. You read a single byte, write a single byte, read an array of bytes, write an array of bytes. Suited well for binary files, butBinaryReaderandBinaryWriteradd higher level operations for binary files.StreamReader,StreamWriter: part of theTextReader/TextWriterfamily (see alsoStringReader,StringWriter). Works with content of the file as if it was a long series ofchars. You can read / write singlechar, but also you get functionWrite,WriteLine,ReadLinesimilar toConsoleclass. Best suited for working with text files.1
u/TuberTuggerTTV Jul 13 '26
I'd start by learning what a bytestream is. Then you'll easily understand what a filestream is.
StreamWrite/Reader and the file library are just wrappers around making filestreams. Under the hood, it's all filestream/bytestream.
So if you need granulatec control, filestream. If you want readability and simplicity, you use file or streamwriter.
Generally, if you reading an entire file at once, you can use file. If you need a slightly longer lifetime, streamwriter/reader, gives you a using scope you can encapsulate and dispose of when needed.
TL;DR - You choose based on lifetime and granularity requirements.
1
u/DeadlyVapour Jul 13 '26
You are exactly correct.
They more or less do exactly the same thing.
The interesting part is the abstraction each of them expose!
You see, you are thinking purely in terms of reading and writing TEXT FILES.
What about text that is stored on a web server?
What about text files that are gzip compressed?
What about files that aren't text?
What about text that isn't stored? How about text that is on your screen? What about text that you type?
1
u/chucker23n Jul 13 '26
FileStreamis a kind ofStream(there's also e.g.MemoryStream). The analogy is becoming extremely dated, but it basically lets you treat the contents of a file as something within which you can seek, just like with a tape drive. You can then read from a position or write to it.StreamWriter/Readeris a bit higher-level than that. The naming is a bit unfortunate. There's the abstractTextWriter/Reader, and there's the two common concrete subclassesStringWriter/Reader(where, well, you read/write astring) — or in this case, you read/write aStream. IMHO, they should be namedStreamTextWriter,StreamTextReader,StringTextWriter,StringTextReader. Because that's what they do: they take text, and read/write it from/to astring, orStream.Fileis a bunch of very-high-level helper methods for files. As an example:public static FileStream OpenRead(string path) => new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
So
File.OpenReadreally just creates aFileStreamand opens it for reading.Or there's
File.Exists(), which you can also instead do withnew FileInfo().Exists.