私は.net 4.0を使用しており、アップロードと呼ばれる方法で残りのwcfサービスを使用してファイルをアップロードし、ダウンロードと呼ばれる方法を使用して同じ残りのサービスを使用してダウンロードしようとしています。ストリーム データを wcf サービスに送信するコンソール アプリケーションがあり、同じコンソール アプリケーションがサービスからダウンロードされます。コンソール アプリケーションは、WebChannelFactory を使用してサービスに接続し、操作します。
これはコンソールアプリのコードです
StreamReader fileContent = new StreamReader(fileToUpload, false);
webChannelServiceImplementation.Upload(fileContent.BaseStream );
これはwcfサービスコードです
public void Upload(Stream fileStream)
{
long filebuffer = 0;
while (fileStream.ReadByte()>0)
{
filebuffer++;
}
byte[] buffer = new byte[filebuffer];
using (MemoryStream memoryStream = new MemoryStream())
{
int read;
while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, read);
}
File.WriteAllBytes(path, buffer);
}
}
このステップでファイルを調べると、コンソール アプリから送信された元のファイルと同じサイズ (キロバイト単位) であることがわかりますが、ファイルを開くと内容がありません。ファイルは、Excel や Word ドキュメントなど、任意のファイル タイプにすることができますが、空のファイルとしてサーバーに送信されます。すべてのデータはどこに消えたのですか?
私がやっている理由はfileStream.ReadByte()>0
、ネットワーク経由で転送するときにバッファの長さが見つからないことをどこかで読んだためです(これが、サービスupload
メソッドでストリームの長さを取得しようとしたときに例外が発生した理由です)。byte[] buffer = new byte[32768];
これが、バイト配列が固定されている多くのオンラインの例に示されているように使用しない理由です。
サービスからのダウンロード中に、wcf サービス側でこのコードを使用します
public Stream Download()
{
return new MemoryStream(File.ReadAllBytes("filename"));
}
そして、私が持っているコンソールアプリ側で
Stream fileStream = webChannelServiceImplementation.Download();
//find size of buffer
long size= 0;
while (fileStream .ReadByte() > 0)
{
size++;
}
byte[] buffer = new byte[size];
using (Stream memoryStream = new MemoryStream())
{
int read;
while ((read = fileContents.Read(buffer, 0, buffer.Length)) > 0)
{
memoryStream.Write(buffer, 0, read);
}
File.WriteAllBytes("filename.doc", buffer);
}
上記のアップロード コードを使用して以前にアップロードしたファイルをダウンロードし、アップロードされたファイルのサイズが 200 KB であったにもかかわらず、サイズが 16 KB しかないため、このダウンロードされたファイルも空白になります。
コードの何が問題になっていますか? どんな助けでも感謝します。