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();