开发者

c# 2.0 file handling Questions

FileStream fs = new FileStream("Myfile.Txt",FileMode.Open,FileAccess.Read);
StreamReader sr= new Streamreader(fs);
s开发者_StackOverflow中文版r.BaseStream.Seek(0,SeekOrigin.Begin);

In this Code What is the use of BaseStream in this Code.?

Seek is Method , sr is an Object of Class StreamReader then What is BaseStream


sr.BaseStream returns the underlying stream where the stream reader reads from, you can use this to operate directly on the stream.

In your sample sr.BaseStream and the FileStream fs are the same thing.

More info: http://msdn.microsoft.com/en-us/library/system.io.streamreader.basestream.aspx

Usually though you would like to work with the StreamReader itself, because this abstracts away some of the difficulties when working with streams. If you give an example how you would like to use the stream then I can see if I can give a possibly easier sample using StreamReader


You could have shortened your code:

//FileStream fs = new FileStream("Myfile.Txt",FileMode.Open,FileAccess.Read);
//StreamReader sr= new Streamreader(fs);
StreamReader sr = File.OpenText("Myfile.Txt");   // using-block omitted 
sr.BaseStream.Seek(0,SeekOrigin.Begin);  

And then you can't use fs anymore. There still is a Stream being created, and BaseStream gives you access.

And note you should be careful to flush the Reader before Seeking on the Stream.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜