2012-01-21 4 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自体は、それがデータを文字列表現に復号可能であるということを意味するものではありません。ストリームが確実である場合は、上記の拡張子を使用できます。