3

私は.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 しかないため、このダウンロードされたファイルも空白になります。

コードの何が問題になっていますか? どんな助けでも感謝します。

4

2 に答える 2

2

ここでは、WCF REST サービスを作成しました。 Service.svc.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace UploadSvc
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple,
                 InstanceContextMode = InstanceContextMode.PerCall,
                 IgnoreExtensionDataObject = true,
                 IncludeExceptionDetailInFaults = true)]    
      public class UploadService : IUploadService
    {

        public UploadedFile Upload(Stream uploading)
        {
            var upload = new UploadedFile
            {
                FilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())
            };

            int length = 0;
            using (var writer = new FileStream(upload.FilePath, FileMode.Create))
            {
                int readCount;
                var buffer = new byte[8192];
                while ((readCount = uploading.Read(buffer, 0, buffer.Length)) != 0)
                {
                    writer.Write(buffer, 0, readCount);
                    length += readCount;
                }
            }

            upload.FileLength = length;

            return upload;
        }

        public UploadedFile Upload(UploadedFile uploading, string fileName)
        {
            uploading.FileName = fileName;
            return uploading;
        }
    }
}

Web.config

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime executionTimeout="100000" maxRequestLength="20000000"/>
  </system.web>
  <system.serviceModel>
    <bindings>
      <webHttpBinding>
        <binding maxBufferSize="2147483647"
                 maxBufferPoolSize="2147483647"
                 maxReceivedMessageSize="2147483647"
                 transferMode="Streamed"
                 sendTimeout="00:05:00" closeTimeout="00:05:00" receiveTimeout="00:05:00">
          <readerQuotas  maxDepth="2147483647"
                         maxStringContentLength="2147483647"
                         maxArrayLength="2147483647"
                         maxBytesPerRead="2147483647"
                         maxNameTableCharCount="2147483647"/>
          <security mode="None" />
        </binding>
      </webHttpBinding>
    </bindings>
    <behaviors>
      <endpointBehaviors>
        <behavior name="defaultEndpointBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="defaultServiceBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="UploadSvc.UploadService" behaviorConfiguration="defaultServiceBehavior">
        <endpoint address="" behaviorConfiguration="defaultEndpointBehavior"
          binding="webHttpBinding" contract="UploadSvc.IUploadService"/>
      </service>
    </services>    
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

Consumer.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Cache;
using System.Text;

namespace UploadSvcConsumer
{
    class Program
    {
        static void Main(string[] args)
        {
            //WebClient client = new WebClient();
            //client.UploadData("http://localhost:1208/UploadService.svc/Upload",)
            //string path = Path.GetFullPath(".");
            byte[] bytearray=null ;
            //throw new NotImplementedException();
            Stream stream =
                new FileStream(
                    @"C:\Image\hanuman.jpg"
                    FileMode.Open);
                stream.Seek(0, SeekOrigin.Begin);
                bytearray = new byte[stream.Length];
                int count = 0;
                while (count < stream.Length)
                {
                    bytearray[count++] = Convert.ToByte(stream.ReadByte());
                }

            string baseAddress = "http://localhost:1208/UploadService.svc/";
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseAddress + "Upload");
            request.Method = "POST";
            request.ContentType = "text/plain";
            request.KeepAlive = false;
            request.ProtocolVersion = HttpVersion.Version10;
            Stream serverStream = request.GetRequestStream();
            serverStream.Write(bytearray, 0, bytearray.Length);
            serverStream.Close();
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                int statusCode = (int)response.StatusCode;
                StreamReader reader = new StreamReader(response.GetResponseStream());

            }

        }
    }
}
于 2014-05-26T18:44:46.830 に答える