C#写的WebService读取文件到byte[]和读取文件内容到string,代码如下:
[WebMethod]
public byte[] dowloadFile()
{
FileStreamreader = null;
stringfilePath = "C:/Inetpub/wwwroot/ws/wrar38b2sc.exe";
try
{
reader = new FileStream(filePath, FileMode.Open,FileAccess.Read);
byte[] bytes = new byte[reader.Length];
reader.Read(bytes, 0, Convert.ToInt32(reader.Length));
reader.Close();
return bytes;
}
catch(Exception ex)
{
throw ex;
}
finally
{
reader.Close();
}
}
[WebMethod]
public string ReadFileToString()
{
StreamReader sr =File.OpenText("C:/Inetpub/wwwroot/ws/test.txt");
StringBuilder sb = new StringBuilder();
while(!sr.EndOfStream)
{
sb.Append(sr.ReadLine());
}
sr.Close();
returnsb.ToString();
}
C++中调用WebService下载文件
//在工程中添加web引用,添加成功后,既可以编写代码如下
#include "stdafx.h"
#include "WebService.h"
#include <comdef.h>
using namespace Service;
using namespace std;
//调用返回值是字符串类型的WebService方法
void ReadFileToString()
{
CoInitialize(NULL);
HRESULT hr =S_OK;
BSTR hiResult;
CService*myService = new CService; //代理对象,这个对象能从类视图中看到
//myService->SetUrl(L"http://192.168.1.158/ws/Service.asmx");
hr =myService->ReadFileToString(&hiResult);
_bstr_t bb =hiResult;
char* c = bb;
if(FAILED(hr))
{
printf("ReadFileToString调用失败\n");
}
else
{
printf("ReadFileToString调用结果:%s\n",c);
}
SysFreeString(hiResult);
delete myService;
CoUninitialize();
}
//调用返回值是byte[]类型的WebService方法,并转成对应文件
void dowloadFile()
{
//当下来的文件名称,因为WebService方法只返回了文件内容,没有文件名称
//
char *fileName = "wrar38b2sc.exe";
CoInitialize(NULL);
HRESULT hr =S_OK;
ATLSOAP_BLOB hiResult;
CService*myService = new CService; //代理对象,这个对象能从类视图中看到
//发布之后的WebSerivce地址,可以写,也可以不写,我在不写的情况下执行成功
//myService->SetUrl(L"http://192.168.1.158/ws/Service.asmx");
hr =myService->dowloadFile(&hiResult);
unsigned char* c= hiResult.data;
if(FAILED(hr))
{
printf("dowloadFile调用失败\n");
}
else
{
printf("dowloadFile调用结果:%s\n",c);
}
FILE*fp;
fp = fopen(fileName, (const char*)("wb"));
fwrite(hiResult.data, hiResult.size, 1,fp);
free(hiResult.data);
fclose(fp);
delete myService;
CoUninitialize();
//执行文件
WinExec(fileName, SW_SHOW);
}