2012-01-21 39 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本身並不意味着它的數據都被解碼爲字符串表示。如果你確定你的流是,你可以使用上面的擴展名。