development

.NET의 스트림에서 MemoryStream을 얻는 방법은 무엇입니까?

big-blog 2020. 12. 2. 21:34
반응형

.NET의 스트림에서 MemoryStream을 얻는 방법은 무엇입니까?


MemoryStream파일 경로에서 를 여는 다음 생성자 메서드가 있습니다 .

MemoryStream _ms;

public MyClass(string filePath)
{
    byte[] docBytes = File.ReadAllBytes(filePath);
    _ms = new MemoryStream();
    _ms.Write(docBytes, 0, docBytes.Length);
}

Stream파일 경로 대신 을 허용하도록 변경해야 합니다. 객체 MemoryStream에서 를 얻는 가장 쉽고 / 가장 효율적인 방법은 Stream무엇입니까?


파일 이름 대신 Stream을 허용하도록 클래스를 수정하는 경우 MemoryStream으로 변환하지 마십시오. 기본 Stream이 작업을 처리하도록합니다.

public class MyClass
{ 
    Stream _s;

    public MyClass(Stream s) { _s = s; }
}

그러나 내부 작업을 위해 MemoryStream이 정말로 필요한 경우 소스 스트림에서 MemoryStream으로 데이터를 복사해야합니다.

public MyClass(Stream stream)
{
    _ms = new MemoryStream();
    CopyStream(stream, _ms);
}

// Merged From linked CopyStream below and Jon Skeet's ReadFully example
public static void CopyStream(Stream input, Stream output)
{
    byte[] buffer = new byte[16*1024];
    int read;
    while((read = input.Read (buffer, 0, buffer.Length)) > 0)
    {
        output.Write (buffer, 0, read);
    }
}

.NET 4에서는 다른 답변에 나열된 홈 브루 방법 대신 Stream.CopyTo사용 하여 스트림을 복사 할 수 있습니다 .

MemoryStream _ms;

public MyClass(Stream sourceStream)

    _ms = new MemoryStream();
    sourceStream.CopyTo(_ms);
}

이것을 사용하십시오 :

var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);

이 변환됩니다 StreamMemoryStream.


Stream 개체의 모든 데이터를 byte[]버퍼 로 읽어 들인 다음 MemoryStream생성자를 통해 전달해야합니다 . 사용중인 스트림 개체 유형에 대해 더 구체적으로 지정하는 것이 좋습니다. Stream매우 일반적이며 Length속성을 구현하지 않을 수 있으므로 데이터를 읽을 때 유용합니다.

다음은 몇 가지 코드입니다.

public MyClass(Stream inputStream) {
    byte[] inputBuffer = new byte[inputStream.Length];
    inputStream.Read(inputBuffer, 0, inputBuffer.Length);

    _ms = new MemoryStream(inputBuffer);
}

경우 Stream객체가 구현하지 않는 Length속성을, 다음과 같이 구현해야합니다 :

public MyClass(Stream inputStream) {
    MemoryStream outputStream = new MemoryStream();

    byte[] inputBuffer = new byte[65535];
    int readAmount;
    while((readAmount = inputStream.Read(inputBuffer, 0, inputBuffer.Length)) > 0)
        outputStream.Write(inputBuffer, 0, readAmount);

    _ms = outputStream;
}

한 스트림의 콘텐츠를 다른 스트림으로 복사하려면 어떻게합니까?

저것 좀 봐. 스트림을 받아들이고 메모리에 복사합니다. 당신은 사용하지 말아야 .Length단지를 위해 Stream그것을 반드시 모든 콘크리트 스트림에서 구현되지 않기 때문에.


이 확장 방법 조합을 사용합니다.

    public static Stream Copy(this Stream source)
    {
        if (source == null)
            return null;

        long originalPosition = -1;

        if (source.CanSeek)
            originalPosition = source.Position;

        MemoryStream ms = new MemoryStream();

        try
        {
            Copy(source, ms);

            if (originalPosition > -1)
                ms.Seek(originalPosition, SeekOrigin.Begin);
            else
                ms.Seek(0, SeekOrigin.Begin);

            return ms;
        }
        catch
        {
            ms.Dispose();
            throw;
        }
    }

    public static void Copy(this Stream source, Stream target)
    {
        if (source == null)
            throw new ArgumentNullException("source");
        if (target == null)
            throw new ArgumentNullException("target");

        long originalSourcePosition = -1;
        int count = 0;
        byte[] buffer = new byte[0x1000];

        if (source.CanSeek)
        {
            originalSourcePosition = source.Position;
            source.Seek(0, SeekOrigin.Begin);
        }

        while ((count = source.Read(buffer, 0, buffer.Length)) > 0)
            target.Write(buffer, 0, count);

        if (originalSourcePosition > -1)
        {
            source.Seek(originalSourcePosition, SeekOrigin.Begin);
        }
    }

public static void Do(Stream in)
{
    _ms = new MemoryStream();
    byte[] buffer = new byte[65536];
    while ((int read = input.Read(buffer, 0, buffer.Length))>=0)
        _ms.Write (buffer, 0, read);
}

byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}

간단하게 다음을 수행 할 수 있습니다.

var ms = new MemoryStream(File.ReadAllBytes(filePath));

스트림 위치는 0이고 사용할 준비가되었습니다.

참고URL : https://stackoverflow.com/questions/3212707/how-to-get-a-memorystream-from-a-stream-in-net

반응형