あるストリームの内容を別のストリームにコピーする最良の方法は何ですか? これのための標準的なユーティリティメソッドはありますか?
13 に答える
.NET 4.5以降、Stream.CopyToAsync
メソッドがあります
input.CopyToAsync(output);
Task
これは、次のように、完了時に続行できるa を返します。
await input.CopyToAsync(output)
// Code from here on will be run in a continuation.
への呼び出しが行われる場所に応じて、CopyToAsync
後続のコードはそれを呼び出した同じスレッドで続行される場合と続行されない場合があることに注意してください。
SynchronizationContext
呼び出し時にキャプチャされたはawait
、継続が実行されるスレッドを決定します。
さらに、この呼び出し (およびこれは変更される可能性のある実装の詳細です) は、引き続き読み取りと書き込みをシーケンスします (I/O 完了時にブロックされているスレッドを無駄にしません)。
.NET 4.0以降、Stream.CopyTo
メソッドがあります
input.CopyTo(output);
.NET 3.5 以前の場合
これを支援するためにフレームワークに組み込まれているものは何もありません。次のように、コンテンツを手動でコピーする必要があります。
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}
注 1: このメソッドを使用すると、進行状況を報告できます (これまでに読み取った x バイト...)
注 2: 固定バッファー サイズを使用して、input.Length
. その長さは利用できないかもしれないので!ドキュメントから:
Stream から派生したクラスがシークをサポートしていない場合、Length、SetLength、Position、および Seek を呼び出すと、NotSupportedException がスローされます。
MemoryStream
もっている.WriteTo(outstream);
および.NET 4.0には.CopyTo
通常のストリームオブジェクトがあります。
.NET 4.0:
instream.CopyTo(outstream);
以下の拡張メソッドを使用します。1 つのストリームが MemoryStream の場合のオーバーロードが最適化されています。
public static void CopyTo(this Stream src, Stream dest)
{
int size = (src.CanSeek) ? Math.Min((int)(src.Length - src.Position), 0x2000) : 0x2000;
byte[] buffer = new byte[size];
int n;
do
{
n = src.Read(buffer, 0, buffer.Length);
dest.Write(buffer, 0, n);
} while (n != 0);
}
public static void CopyTo(this MemoryStream src, Stream dest)
{
dest.Write(src.GetBuffer(), (int)src.Position, (int)(src.Length - src.Position));
}
public static void CopyTo(this Stream src, MemoryStream dest)
{
if (src.CanSeek)
{
int pos = (int)dest.Position;
int length = (int)(src.Length - src.Position) + pos;
dest.SetLength(length);
while(pos < length)
pos += src.Read(dest.GetBuffer(), pos, length - pos);
}
else
src.CopyTo((Stream)dest);
}
.NET Framework 4 では、System.IO 名前空間の Stream クラスの新しい "CopyTo" メソッドが導入されました。このメソッドを使用して、あるストリームを別のストリーム クラスの別のストリームにコピーできます。
この例を次に示します。
FileStream objFileStream = File.Open(Server.MapPath("TextFile.txt"), FileMode.Open);
Response.Write(string.Format("FileStream Content length: {0}", objFileStream.Length.ToString()));
MemoryStream objMemoryStream = new MemoryStream();
// Copy File Stream to Memory Stream using CopyTo method
objFileStream.CopyTo(objMemoryStream);
Response.Write("<br/><br/>");
Response.Write(string.Format("MemoryStream Content length: {0}", objMemoryStream.Length.ToString()));
Response.Write("<br/><br/>");
実際には、ストリーム コピーを行うための、より手間のかからない方法があります。ただし、これはファイル全体をメモリに保存できることを意味することに注意してください。数百メガバイト以上になるファイルを扱う場合は、注意せずにこれを使用しないでください。
public static void CopySmallTextStream(Stream input, Stream output)
{
using (StreamReader reader = new StreamReader(input))
using (StreamWriter writer = new StreamWriter(output))
{
writer.Write(reader.ReadToEnd());
}
}
注: バイナリ データと文字エンコーディングに関する問題もあるかもしれません。
「CopyStream」の実装を区別する基本的な質問は次のとおりです。
- 読み取りバッファのサイズ
- 書き込みのサイズ
- 複数のスレッドを使用できますか (読み取り中に書き込みます)。
これらの質問に対する答えは、CopyStream の実装が大きく異なり、使用しているストリームの種類と最適化しようとしているものに依存します。「最良の」実装では、ストリームが読み書きしている特定のハードウェアを知る必要さえあります。
あるストリームから別のストリームにコピーする非同期の方法をカバーしている回答はないため、ポート転送アプリケーションでデータをあるネットワークストリームから別のネットワークストリームにコピーするために正常に使用したパターンを次に示します。パターンを強調するための例外処理がありません。
const int BUFFER_SIZE = 4096;
static byte[] bufferForRead = new byte[BUFFER_SIZE];
static byte[] bufferForWrite = new byte[BUFFER_SIZE];
static Stream sourceStream = new MemoryStream();
static Stream destinationStream = new MemoryStream();
static void Main(string[] args)
{
// Initial read from source stream
sourceStream.BeginRead(bufferForRead, 0, BUFFER_SIZE, BeginReadCallback, null);
}
private static void BeginReadCallback(IAsyncResult asyncRes)
{
// Finish reading from source stream
int bytesRead = sourceStream.EndRead(asyncRes);
// Make a copy of the buffer as we'll start another read immediately
Array.Copy(bufferForRead, 0, bufferForWrite, 0, bytesRead);
// Write copied buffer to destination stream
destinationStream.BeginWrite(bufferForWrite, 0, bytesRead, BeginWriteCallback, null);
// Start the next read (looks like async recursion I guess)
sourceStream.BeginRead(bufferForRead, 0, BUFFER_SIZE, BeginReadCallback, null);
}
private static void BeginWriteCallback(IAsyncResult asyncRes)
{
// Finish writing to destination stream
destinationStream.EndWrite(asyncRes);
}
作業しているストリームの種類によっては、これをより効率的に行う方法がある場合があります。ストリームの一方または両方を MemoryStream に変換できる場合は、GetBuffer メソッドを使用して、データを表すバイト配列を直接操作できます。これにより、フライガイボブによって提起されたすべての問題を抽象化する Array.CopyTo などのメソッドを使用できます。.NET がデータをコピーするための最適な方法を知っていると信頼できます。
残念ながら、本当に簡単な解決策はありません。あなたはそのようなことを試すことができます:
Stream s1, s2;
byte[] buffer = new byte[4096];
int bytesRead = 0;
while (bytesRead = s1.Read(buffer, 0, buffer.Length) > 0) s2.Write(buffer, 0, bytesRead);
s1.Close(); s2.Close();
しかし、読み取るものが何もない場合、Stream クラスの異なる実装が異なる動作をする可能性があるという問題があります。ローカル ハードドライブからファイルを読み取るストリームは、読み取り操作によってディスクから十分なデータが読み取られてバッファーがいっぱいになるまでおそらくブロックされ、ファイルの最後に達した場合はより少ないデータしか返されません。一方、ネットワークからのストリーム読み取りでは、受信するデータが残っている場合でも、返されるデータが少なくなる場合があります。
一般的なソリューションを使用する前に、使用している特定のストリーム クラスのドキュメントを必ず確認してください。
.NET 3.5 以前の場合:
MemoryStream1.WriteTo(MemoryStream2);
簡単で安全 - 元のソースから新しいストリームを作成:
MemoryStream source = new MemoryStream(byteArray);
MemoryStream copy = new MemoryStream(byteArray);
ニックが投稿したストリームを他のストリームにコピーする手順が必要な場合は問題ありませんが、位置のリセットがありません。
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[32768];
long TempPos = input.Position;
while (true)
{
int read = input.Read (buffer, 0, buffer.Length);
if (read <= 0)
return;
output.Write (buffer, 0, read);
}
input.Position = TempPos;// or you make Position = 0 to set it at the start
}
ただし、実行時にプロシージャを使用していない場合は、メモリストリームを使用する必要があります
Stream output = new MemoryStream();
byte[] buffer = new byte[32768]; // or you specify the size you want of your buffer
long TempPos = input.Position;
while (true)
{
int read = input.Read (buffer, 0, buffer.Length);
if (read <= 0)
return;
output.Write (buffer, 0, read);
}
input.Position = TempPos;// or you make Position = 0 to set it at the start