2012-01-21 2 views
1

스트림에 확장 방법 bool StartsWith(string message)을 쓰고 싶습니다. 가장 효율적인 방법은 무엇입니까? 이 같은 뭔가스트림의 확장 방법으로 시작합니다.

+0

먼저 더 구체적인 내용이 필요합니다. 스트림의 확장명을 http://msdn.microsoft.com/ko-kr/library/baketfxw.aspx의 기능을 미러링하도록 지정 하시겠습니까? – Seph

+0

@ 셉; 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 방법이있다 보다 효율적인 결과를 위해 '덩어리'. 물론 Stream 자체가 데이터가 있다는 의미는 아닙니다의

+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; 
} 

문자열 표현으로 복호입니다. 스트림이 확실하다면 위의 확장자를 사용할 수 있습니다.

관련 문제