2012-01-21 42 views
1

我想为流编写bool StartsWith(string message)扩展方法。什么是最有效的方法?StartsWith流的扩展方法

+0

首先,您需要更具体一点,您的意思是您想要一个流有一个扩展镜像的功能http://msdn.microsoft.com/en-us/library/baketfxw.aspx – Seph

+0

@Seph;我想为Stream编写一个.net扩展方法。你给的链接是字符串。 – Faisal

回答

2

开始这样的事情...

public static bool StartsWith(Stream stream this, string value) 
{ 
    using(reader = new StreamReader(stream)) 
    { 
    string str = reader.ReadToEnd(); 
    return str.StartsWith(value); 
    } 
} 

然后优化...我会离开这个作为练习你,StreamReader有各种Read方法,这将让你在更小的读取流'块'为更有效的结果。

+2

在这种情况下,使用StreamReader并不是一个好主意,因为它会在阅读器处置时关闭流,这很可能是意想不到的。 – ChrisWue

1
static bool StartsWith(this Stream stream, string value, Encoding encoding, out string actualValue) 
{ 
    if (stream == null) { throw new ArgumentNullException("stream"); } 
    if (value == null) { throw new ArgumentNullException("value"); } 
    if (encoding == null) { throw new ArgumentNullException("encoding"); } 

    stream.Seek(0L, SeekOrigin.Begin); 

    int count = encoding.GetByteCount(value); 
    byte[] buffer = new byte[count]; 
    int read = stream.Read(buffer, 0, count); 

    actualValue = encoding.GetString(buffer, 0, read); 

    return value == actualValue; 
} 

过程中Stream本身并不意味着它的数据都被解码为字符串表示。如果你确定你的流是,你可以使用上面的扩展名。