VS 2008 mfc 智能应用程序 调用 C# webservice.(一)

进过几天的苦战,终于搞定VS 2008 mfc 智能应用程序 调用 C# webservice.,实现PDA 与 服务器的通信 与文件上传,深刻体会到 IT 男是个青春饭。。。。。你嘛!

一开始的思路 只是想实现 PDA 与服务器的文件传输,纠结于 MFC socket  还是Web服务?  socket?服务?socket 服务?。。。。。。。。。。。。。

写了个短消息发送接收通信程序,但是一想到发送文件,要分包啦,多线程啦,客户端 ,服务器。。。烦得一米,想想还是采用webservice  吧,C#  webservice  不是很简单的东西嘛,结果证明这条道路有蛋疼只能自己体会 !!!!!

1测试1 VS 2008  MFC 窗体应用程序+C# websetvice

 

1.1  websetvice 发布

    [WebMethod]
    public string uplowadfile(Byte[] fidata,string filename)
    {

        string  str= System.Text.Encoding.Default.GetString(fidata);
           try
        {
          //  MemoryStream ms = new MemoryStream(fidata);
            string filepath = Server.MapPath("~/data/") + filename;
              FileStream stream = new FileStream(filepath , FileMode.OpenOrCreate);
         
            StreamWriter swWriter = new StreamWriter(stream, System.Text.Encoding.Default);  //使用与系统一致的编码方式

            string[] mystr = str.Split('\n');

            foreach (string r in mystr)
            swWriter.WriteLine(r);
            swWriter.Close();
             
           return "finish";


        }
        catch(Exception e)
        {

            return "error"+e.Message;

        }

    }

 

 注意点 参数 Byte[] fidata, 如果想上传图片,必须是二进制流的形式,如果是文本文件 无所谓 Byte[] fidata,还是string

           Server.MapPath("~/data/"),表示 虚拟目录下data文件夹,我以新建虚拟目录形式发布服务

          注意 编码 防止乱码

 

 

1.2 客户端调用,本以为这个C# 应用程序一样,很简单 ,没想到。。。。。。

     添加->引用->Web 引用->     灰的!!!!你嘛。。。。。(原来VS 08 去掉了)

    解决方法:项目-属性-常规-公共语言支持 就行了 ,项目自动添加了  所需的.h 文件

 




#include "WebService.h"

#include <string.h>
using namespace localhost;

using namespace System;

using namespace System::Runtime::InteropServices;

FILE *fp; int flen; char *p; byte *byp;  Service ser; if((fp=fopen("G:\\A5.txt","r"))==NULL) { return ; } fseek(fp,0,SEEK_END); flen=ftell(fp); p=(char*)malloc(flen); byp=(byte*)malloc(flen); memset(p,0,flen); //*********************************************记得初始化,否则有乱码 if(p==NULL) { fclose(fp); } fseek(fp,0,SEEK_SET); fread(p,flen,1,fp); p[flen]=0; TRACE("p:%s",p); fclose(fp); *byp=*p; TRACE("byte:%s",p); int len=strlen(p); cli::array< Byte >^ aa = gcnew array< Byte >(len+2); Marshal::Copy((IntPtr)p,aa,0,len); char filename[]="123.txt"; //CString result=ser.uplowadfile(aa); CString result=ser.uplowadfile(aa,gcnew String(filename));

 

       不能把读取的文件 存入Byte[],因为服务是托管的,必须  转化 cli::array< Byte >^ aa = gcnew array< Byte >(len+2); ,因为cli::array 才是托管和非托管通用的。(托管和非托管混合编程,中的数据结构类型转化 什么的 ,哥不懂啊 !!!!)

 好了 调用成功

 

 

 

 

posted on 2012-05-13 16:15  markygis  阅读(1157)  评论(0编辑  收藏  举报