接受并返回C#WebService的文件

时间:2012-03-28 17:14:54

标签: c# web-services

如何在C#中创建一个Web服务,接受文件,然后在一次调用中同时返回一个文件(同步)。 我要做的是创建一个接受和MS Office文档的WebService,将该文档转换为PDF然后将该文件返回给调用者(在我的情况下,我使用Java作为客户端)

4 个答案:

答案 0 :(得分:2)

正如silvermind在评论中所说,最好的选择是在你的网络服务中接受并返回一个字节数组。

您可以使用如下方法将文件作为bytearray加载:

public byte[] FileToByteArray(string _FileName)
{
    byte[] _Buffer = null;

    try
    {
        System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
        long _TotalBytes = new System.IO.FileInfo(_FileName).Length;
        _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);
        _FileStream.Close();
        _FileStream.Dispose();
        _BinaryReader.Close();
    }
    catch (Exception _Exception)
    {
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
    }
    return _Buffer;
}

此外,如果您已将Web服务实现为WCF服务,则可能需要调整一些设置以增加可以发送的信息数量和超时。这是允许这种情况的绑定配置示例。 (只有一个样本,可能不符合您的需求)

 <binding name="WebServiceBinding" closeTimeout="00:02:00"
            openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:02:00"
            allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
            maxBufferPoolSize="524288" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"
            messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
            useDefaultWebProxy="true">
          <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
              maxBytesPerRead="4096" maxNameTableCharCount="16384" />
          <security mode="None">
            <transport clientCredentialType="None" proxyCredentialType="None"
                realm="" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>

答案 1 :(得分:0)

您可以将少量二进制数据编码为base64字符串。

答案 2 :(得分:0)

这里有几个来自不同来源的教程,它还取决于你使用的是什么wcf或asmx。我还认为你必须创建两个独立的函数和另一个同时调用send和revive的函数,尽管你可能希望在收到它之前有一些时间让发送发生。

http://support.microsoft.com/kb/318425

http://www.zdnetasia.com/create-a-simple-file-transfer-web-service-with-net-39251815.htm

https://stackoverflow.com/questions/4530045/how-to-transfer-file-through-web-service

答案 3 :(得分:0)

最简单的方法是将ASP.net MVC3框架的基本库集成到基本Webproject中,然后使用单个方法编写一个简单的MVC控制器,该方法返回FileResult类型的对象。

斯科特·汉塞尔曼(Scott Hanselman)发表了一篇关于在几分钟内完成这项工 http://www.hanselman.com/blog/IntegratingASPNETMVC3IntoExistingUpgradedASPNET4WebFormsApplications.aspx

它工作得非常好,并且在不到3分钟内完成(在MVC3框架集成之后)。已经有关于在MVC中返回文件的stackoverflow帖子: How to create file and return it via FileResult in ASP.NET MVC?

问候,