Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

c# - FileStream vs/differences StreamWriter?

Question:

What is different between FileStream and StreamWriter in .Net?

What context are you supposed to use it? What is their advantage and disadvantage?

Is it possible to combine these two into one?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What is different between FileStream and StreamWriter in dotnet?

A FileStream is a Stream. Like all Streams it only deals with byte[] data.

A StreamWriter : TextWriter, is a Stream-decorator. A TextWriter encodes Text data like string or char to byte[] and then writes it to the linked Stream.

What context are you supposed to use it? What is their advantage and disadvantage?

You use a bare FileStream when you have byte[] data. You add a StreamWriter when you want to write text. Use a Formatter or a Serializer to write more complex data.

Is it possible to combine these two into one?

Yes. You always need a Stream to create a StreamWriter. The helper method System.IO.File.CreateText("path") will create them in combination and then you only have to Dispose() the outer writer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...