どのように変換するストリームをbyte[]クライアントまで、フルのC#?[重複]

StackOverflow https://stackoverflow.com/questions/1080442

  •  22-08-2019
  •  | 
  •  

質問

この質問に答えはこちら

ある単純な方法や手段に変換するには Streambyte[] C#?

役に立ちましたか?

解決

タグのように次の関数を呼び出します
byte[] m_Bytes = StreamHelper.ReadToEnd (mystream);

機能:

public static byte[] ReadToEnd(System.IO.Stream stream)
    {
        long originalPosition = 0;

        if(stream.CanSeek)
        {
             originalPosition = stream.Position;
             stream.Position = 0;
        }

        try
        {
            byte[] readBuffer = new byte[4096];

            int totalBytesRead = 0;
            int bytesRead;

            while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
            {
                totalBytesRead += bytesRead;

                if (totalBytesRead == readBuffer.Length)
                {
                    int nextByte = stream.ReadByte();
                    if (nextByte != -1)
                    {
                        byte[] temp = new byte[readBuffer.Length * 2];
                        Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
                        Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
                        readBuffer = temp;
                        totalBytesRead++;
                    }
                }
            }

            byte[] buffer = readBuffer;
            if (readBuffer.Length != totalBytesRead)
            {
                buffer = new byte[totalBytesRead];
                Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
            }
            return buffer;
        }
        finally
        {
            if(stream.CanSeek)
            {
                 stream.Position = originalPosition; 
            }
        }
    }

他のヒント

私が知っている最短ソリューション:

using(var memoryStream = new MemoryStream())
{
  sourceStream.CopyTo(memoryStream);
  return memoryStream.ToArray();
}

の.NET Framework 4以降では、Streamクラスを使用すると、使用できる組み込みのCopyToの方法があります。

フレームワークの以前のバージョンでは、持っている便利なヘルパー関数があります:

public static void CopyStream(Stream input, Stream output)
{
    byte[] b = new byte[32768];
    int r;
    while ((r = input.Read(b, 0, b.Length)) > 0)
        output.Write(b, 0, r);
}

次にMemoryStreamにコピーし、それにGetBufferを呼び出すために上記のいずれかの方法を使用します:

var file = new FileStream("c:\\foo.txt", FileMode.Open);

var mem = new MemoryStream();

// If using .NET 4 or later:
file.CopyTo(mem);

// Otherwise:
CopyStream(file, mem);

// getting the internal buffer (no additional copying)
byte[] buffer = mem.GetBuffer();
long length = mem.Length; // the actual length of the data 
                          // (the array may be longer)

// if you need the array to be exactly as long as the data
byte[] truncated = mem.ToArray(); // makes another copy

編集のもともと私はStreamプロパティをサポートLengthためのジェイソンの答えを使用して提案しました。それはStreamは必ずしも真ではない単一Read、中にすべての内容を返すことを想定ので、しかし、それは欠陥を持っていた(例えば、ないSocketため。)Stream実装の例があるかどうかはわかりませんLengthをサポートしていないが、あなたが要求するよりも短いチャンクでデータを返すかもしれませんが、誰もがStreamを継承することができ、これは簡単に場合可能性があります。

BCLで

これは、上記の一般的なソリューションを使用するには、ほとんどの場合のために、おそらく簡単ですが、あなたはbigEnoughある配列に直接読みたいんでした想定ます:

byte[] b = new byte[bigEnough];
int r, offset;
while ((r = input.Read(b, offset, b.Length - offset)) > 0)
    offset += r;

つまり、繰り返しReadを呼び出し、あなたがでデータを格納することになる位置を移動します。

    byte[] buf;  // byte array
    Stream stream=Page.Request.InputStream;  //initialise new stream
    buf = new byte[stream.Length];  //declare arraysize
    stream.Read(buf, 0, buf.Length); // read from stream to byte array

私は、この拡張クラスを使用します:

public static class StreamExtensions
{
    public static byte[] ReadAllBytes(this Stream instream)
    {
        if (instream is MemoryStream)
            return ((MemoryStream) instream).ToArray();

        using (var memoryStream = new MemoryStream())
        {
            instream.CopyTo(memoryStream);
            return memoryStream.ToArray();
        }
    }
}

ちょうどあなたのソリューションにクラスをコピーして、すべてのストリーム上でそれを使用することができます:

byte[] bytes = myStream.ReadAllBytes()

は、すべて私のストリームのための素晴らしい作品とコードの多くを節約します! もちろん、必要に応じてパフォーマンスを向上させるために、ここで他のアプローチのいくつかを使用するには、この方法を修正することができますが、私はそれをシンプルに維持したい。

Byte[] Content = new BinaryReader(file.InputStream).ReadBytes(file.ContentLength);

[OK]を、多分私はここで何かが欠けていますが、これは、私はそれを行う方法です。

public static Byte[] ToByteArray(this Stream stream) {
    Int32 length = stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(stream.Length);
    Byte[] buffer = new Byte[length];
    stream.Read(buffer, 0, length);
    return buffer;
}

あなたがモバイルデバイスまたは他のファイルを投稿する場合は、

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

クイックと汚いテクニックます:

    static byte[] StreamToByteArray(Stream inputStream)
    {
        if (!inputStream.CanRead)
        {
            throw new ArgumentException(); 
        }

        // This is optional
        if (inputStream.CanSeek)
        {
            inputStream.Seek(0, SeekOrigin.Begin);
        }

        byte[] output = new byte[inputStream.Length];
        int bytesRead = inputStream.Read(output, 0, output.Length);
        Debug.Assert(bytesRead == output.Length, "Bytes read from stream matches stream length");
        return output;
    }

テスト

    static void Main(string[] args)
    {
        byte[] data;
        string path = @"C:\Windows\System32\notepad.exe";
        using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read))
        {
            data = StreamToByteArray(fs);
        }

        Debug.Assert(data.Length > 0);
        Debug.Assert(new FileInfo(path).Length == data.Length); 
    }

あなたは、ストリームの内容をコピーしたいされている場合、私は、[]あなたはバイトにストリームを読みたいなぜ、求めるだろう、私はMemoryStreamをを使用することをお勧めし、メモリストリームにあなたの入力ストリームを書き込むことがあります。

Stream s;
int len = (int)s.Length;
byte[] b = new byte[len];
int pos = 0;
while((r = s.Read(b, pos, len - pos)) > 0) {
    pos += r;
}

もう少し複雑な解決策はnecesaryあるs.LengthInt32.MaxValueを超えています。あなたはメモリにその大きな流れを読むために必要がある場合しかし、あなたはあなたの問題に異なるアプローチを考えることもできます。

編集:あなたのストリームがLengthプロパティをサポートしていない場合は、エリカーの<のhref = "https://stackoverflow.com/questions/1080442/how-to-convert-an-stream-into-a-byteを使用して修正します-in-C / 1080474#1080474" >回避策でます。

public static class StreamExtensions {
    // Credit to Earwicker
    public static void CopyStream(this Stream input, Stream output) {
        byte[] b = new byte[32768];
        int r;
        while ((r = input.Read(b, 0, b.Length)) > 0) {
            output.Write(b, 0, r);
        }
    }
}

[...]

Stream s;
MemoryStream ms = new MemoryStream();
s.CopyStream(ms);
byte[] b = ms.GetBuffer();

また、ジャストインタイムでの部品に読み込み、返されるバイト配列を拡大しようとすることができます:

public byte[] StreamToByteArray(string fileName)
{
    byte[] total_stream = new byte[0];
    using (Stream input = File.Open(fileName, FileMode.Open, FileAccess.Read))
    {
        byte[] stream_array = new byte[0];
        // Setup whatever read size you want (small here for testing)
        byte[] buffer = new byte[32];// * 1024];
        int read = 0;

        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            stream_array = new byte[total_stream.Length + read];
            total_stream.CopyTo(stream_array, 0);
            Array.Copy(buffer, 0, stream_array, total_stream.Length, read);
            total_stream = stream_array;
        }
    }
    return total_stream;
}

「bigEnough」配列ストレッチのビットです。確かに、バッファは「ビッグebough」にする必要がありますが、アプリケーションの適切な設計は、取引や区切り文字を含める必要があります。この構成では、各トランザクションは、プリセット長さは、このようにあなたの配列が特定のバイト数を予測し、適切なサイズのバッファにそれを挿入する必要があります。区切り文字は、トランザクションの整合性を保証するであろうし、各トランザクション内で供給されます。アプリケーションがより良いようにするには、2つのチャンネル(2ソケット)を使用することができます。一つは、データチャネルを使用して転送されるデータトランザクションのサイズおよびシーケンス番号に関する情報を含むことになる固定長の制御メッセージトランザクションを通信します。受信機は、バッファの作成を認めるだろうとだけにしてデータが送信されます。 あなたはバッファとして多次元配列を必要とするよりも、ストリームの送信者を制御することはできません場合。成分の配列は、管理しやすいと予想されるデータの見積もりに基づいて実用的で十分な大きさに十分に小さいだろう。処理ロジックは、後続の素子アレイにおける既知の開始デリミタ、次いで、終了区切り文字を求めることになります。一度終了区切り文字が検出されたデータの廃棄を許可するように再構築しなければならず、新しいバッファは区切り文字と初期バッファ間の関連データを格納するために作成されます。

限りバイト配列にストリームを変換するためのコードとして以下のものである。

Stream s = yourStream;
int streamEnd = Convert.ToInt32(s.Length);
byte[] buffer = new byte[streamEnd];
s.Read(buffer, 0, streamEnd);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top