バイナリStreamの書き出し方法
プログラミング的には難しくないが、
クラスの設計思想に対して私の認識が合わなく一苦労。
いつでも思い出せるようにメモしておく。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Reflection;
namespace readWriteStreamTest {
class Program {
static void Main(string args)
{
WebClient webClient = new WebClient();
using (Stream stream = webClient.OpenRead("http://chart.apis.google.com/chart?cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World")) {
Assembly myAssembly = Assembly.GetEntryAssembly();
string strFilePath = Directory.GetParent(myAssembly.Location) + "\\test.png";
FileStream fileStream = new FileStream(strFilePath, FileMode.Create, FileAccess.Write);
ReadWriteStream(stream, fileStream);
}
}
// readStream is the stream you need to read
// writeStream is the stream you want to write to
static void ReadWriteStream(Stream readStream, Stream writeStream)
{
int Length = 256;
Byte buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer,0,Length);
// write the required bytes
while( bytesRead > 0 )
{
writeStream.Write(buffer,0,bytesRead);
bytesRead = readStream.Read(buffer,0,Length);
}
readStream.Close();
writeStream.Close();
}
}
}