基于.net compact framework 2.0,C#开发windows mobile 5.0程序遇到的一些问题及解决办法...

初学,只能写些小程序,遇到一些问题,幸好通过查MSDN和泡论坛大多都解决了,希望能给同样遇到这些问题的朋友一些启示,功力浅说的不一定对,大家在这里也可以多多指正交流,^_^

1 . 移动设备获取绝对路径
     我们可以通过以下代码 获得运行程序所运行的绝对路径:
                      String apppath = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;
       路径问题很常见,举个例子,我们可以设置一个图片按钮,当点击时改变图片内容起到立体按钮的效果
                apppath = apppath.Substring(0, apppath.LastIndexOf(@"\"));
                apppath = apppath + "\\img";
                string imagePath = Path.Combine(apppath, imgname1);
               Bitmap   _imageBitmap = new Bitmap(imagePath);

2. 有时界面属性改变不会自动改变页面效果,我们需要加一条语句:
              Application.DoEvents();
               就象上面图片按钮变更时也需要用到。

3.  用windows mible 5.0编写GPRS上网调用基于J2EE的WebService的程序时发现.NET精简框架没有System.Net.CookieContainer类,无法保存客户端会话,困扰N久。
后再经人提点,去研究HTTP的运行原理,分析求响应的Http消息头,通过socket连接将repones回返的字串句句分析,解析出SessionId,SessionId大概是一个这个样子的字串Set-Cookie:JSESSIONID=ES56V1MBEVOAAQSNDBESKHN。
在下一次提交request时,调用request.add()方法,把SessionId加入到这次会话中。

4.  需要要在手机上显示比较复杂的图表,当时考虑,把数据传到手机上,再用控件生成图表,找了不少C#的图表控件,可以.NET Compact Framework根本不支持。自己用GUI去画,或者自定义图表控件,又觉得量大麻烦,于是用另一种方式,在服务器端生成图表,一般IMG格式的然后通过字节流输出到手机端显示,OK,一个图几十K到一百多K,挺简单就是GPRS费用高些,哈哈。

5.  程序初始化时加载INI配置文件或者XML数据类型文件这个操作是一般信息软件必备的,当时在网上搜了两个现成的程序,懒得重新写了,大概看了下没有问题就用了,感谢把那些共用程序贴出来的朋友们,再这里再贴一遍,方便大家使用:
举个例子INI读取:
            IniFile NewIni = new IniFile(Globle.ApplicationPath + "\\connect.ini");
            string ip = NewIni.IniReadValue("connectini", "ip");
            string post = NewIni.IniReadValue("connectini", "post");
                 INI写入
     IniFile NewIni = new IniFile(Globle.ApplicationPath + "\\connect.ini");
            NewIni.IniWriteValue("connectini", "ip", urlip);
            NewIni.IniWriteValue("connectini", "post", urlpost);

           Globle.ApplicationPath为程序所在绝对路径
              connect.ini文件内容格式如下:

       [connectini]
              ip=192.168.1.1
              post=80

XML读取:
             Hashtable constantsTable = new Hashtable();
             XmlNodeType[] xmlNType = { XmlNodeType.Element, XmlNodeType.EndElement, XmlNodeType.XmlDeclaration };
            MyXmlReader xRead = new MyXmlReader(Globle.ApplicationPath+"\\constants.xml", null);
            try
            {
                xRead.FilterByNodeType(xmlNType, constantsTable);
            }
            catch (XmlException xmlExp)
            {
                MessageBox.Show(xmlExp.ToString());
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }
            finally
            {
                xRead.Dispose();
            }

//--------------------------------------读写INI的IniFile类
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.IO; 

{
    ///   <summary>
    ///   Ini   的摘要说明。
    ///   </summary>
    public class IniFile

    {

        public string path;

        #region 寫入信息文件
                private void WritePrivateProfileString(string ApplicationName,
                string KeyName, string Value, string FileName) {
            string[] iniItems = new string[0];
            string iniLines = null;
            string iniLine = null;
            string iniItem = null;
            int i, j;
            try {
                //读取INI文件;
                System.IO.StreamReader iniFile = new System.IO.StreamReader(
                        FileName, System.Text.Encoding.Default);
                iniLines = iniFile.ReadToEnd();
                iniFile.Close();
            } catch {
            }

                    //如果信息文件還沒有任何內容,將節點寫到第一行
                    if (iniLines == null) {
                StreamWriter CreatFile = File.CreateText(FileName);
                CreatFile.Close();
                StreamWriter FileWriter = new StreamWriter(FileName, true,
                        System.Text.Encoding.Default);
                FileWriter.WriteLine("[" + ApplicationName + "]");
                FileWriter.WriteLine(KeyName + "=" + Value);
                FileWriter.Close();
                return;
            } else {
                //否則的話得到已有的節點
                iniItems = System.Text.RegularExpressions.Regex.Split(iniLines,
                        "\r\n");
            }
            //以回车符分割,得到每一行
            bool HaveParentNode = false;
                string IniContent = "";
            int IndexLength = 0;
            if (iniItems[iniItems.Length - 1] == "") {
                IndexLength = iniItems.Length - 1;
            } else {
                IndexLength = iniItems.Length;
            }
            for (i = 0; i < IndexLength; i++) {
                iniItem = iniItems[i].Trim();
                if (iniItem[0] == '[' && iniItem[iniItem.Length - 1] == ']') {
                    if (IniContent == "") {
                        IniContent = iniItems[i].ToString();
                    } else {
                        IniContent += "\r\n" + iniItems[i].ToString();
                    }
                    if (iniItems[i].ToString() == "[" + ApplicationName + "]") {
                        HaveParentNode = true;
                        bool HaveNode = false;
                        try {
                            //找到相對應的父節點的話,查找是否有對應的子節點
                            for (j = (i + 1); j < IndexLength; j++) {
                                iniLine = iniItems[j].Trim();
                                if (iniLine[0] == '[' &&
                                    iniLine[iniLine.Length - 1] == ']') {
                                    if (!HaveNode) {
                                        HaveNode = true;
                                        IniContent += "\r\n" + KeyName + "=" +
                                                Value;
                                    }
                                    break;
                                }

                                iniLine = iniItems[j].TrimStart().Replace(
                                        "   ", "");
                                if (iniLine.Substring(0,
                                        Math.Min(KeyName.Length + 1,
                                                 iniLine.Length)).ToUpper() ==
                                    KeyName.ToUpper() + "=") {
                                     
                                            //如果找到了Key匹配
                                            HaveNode = true;
                                    IniContent += "\r\n" + KeyName + "=" +
                                            Value;
                                } else {
                                    IniContent += "\r\n" +
                                            iniItems[j].ToString();
                                }
                            }
                        } catch (System.Exception ex) {
                            ex.ToString();
                        }

                        if (!HaveNode) {
                            HaveNode = true;
                            IniContent += "\r\n" + KeyName + "=" + Value;
                        }
                    } else {
                        for (j = (i + 1); j < IndexLength; j++) {
                            iniLine = iniItems[j].Trim();
                            if (iniLine[0] == '[' &&
                                iniLine[iniLine.Length - 1] == ']') {
                                break;
                            } else {
                                IniContent += "\r\n" + iniItems[j].ToString();
                            }
                        }
                    }
                }
            }

            if (!HaveParentNode) {
                IniContent += "\r\n[" + ApplicationName + "]";
                IniContent += "\r\n" + KeyName + "=" + Value;
            }

            StreamWriter ReplaceFile = File.CreateText(FileName);
            ReplaceFile.Close();
            StreamWriter ReplaceWriter = new StreamWriter(FileName, true,
                    System.Text.Encoding.Default);
            ReplaceWriter.Write(IniContent);
            ReplaceWriter.Close();
        }

        #endregion

                #region 讀取信息文件
                private string GetPrivateProfileString(string ApplicationName,
                string KeyName, string Default, string FileName) {
            string[] iniItems = new string[0];
            string iniLines;
            string iniLine;
            int i, j;
            try {
                //读取INI文件;
                System.IO.StreamReader iniFile = new System.IO.StreamReader(
                        FileName, System.Text.Encoding.Default);
                iniLines = iniFile.ReadToEnd();
                iniFile.Close();
            } catch {
                    return Default;
            }
                    //以回车符分割,得到每一行
                    iniItems = System.Text.RegularExpressions.Regex.Split(
                    iniLines, "\r\n");
                ;
            //遍历每一行
            for (i = 0; i < iniItems.GetLength(0); i++)
                  {
                        //找到匹配值
                        if (iniItems[i].Trim().ToUpper() ==
                            '[' + ApplicationName.Trim().ToUpper() + ']') {
                    //从下一行开始搜索
                    for (j = i + 1; j < iniItems.GetLength(0); j++) {
                        iniLine = iniItems[j].Trim();
                        if (iniLine.Length > 0) {
                            //如果找到了另一个段,那么就越段了,则返回默认值
                            if (iniLine[0] == '[' &&
                                iniLine[iniLine.Length - 1] == ']')
                                return Default;
                        }
                        //去掉所有空格
                        iniLine = iniItems[j].TrimStart().Replace("   ", "");
                        if (iniLine.Substring(0,
                                              Math.Min(KeyName.Length + 1,
                                iniLine.Length)).ToUpper() ==
                            KeyName.ToUpper() + "=") {
                             
                                    //如果找到了Key匹配
                                    return iniItems[j].Substring(iniItems[j].
                                    IndexOf('=') + 1);
                        }
                    }
                    return Default; //没有找到key匹配的,则返回默认值
                }
                }
                        return Default; //返回默认值
        }

        #endregion

                public IniFile(string INIPath) {
            path = INIPath;
        }

        public void IniWriteValue(string Section, string Key, string Value) {
            WritePrivateProfileString(Section, Key, Value, this.path);
        }

        public string IniReadValue(string Section, string Key) {
            return GetPrivateProfileString(Section, Key, "", this.path);
        }

    }
}
//-------------------------------------------------读取XML加载进map的类
//---------------------------------------------------------------------------------------------------
//XmlReader类用于Xml文件的一般读取操作,以下对这个类做简单介绍:
//
//Attributes(属性):
//listBox: 设置该属性主要为了得到客户端控件以便于显示所读到的文件的内容(这里是ListBox控件)
//xmlPath: 设置该属性为了得到一个确定的Xml文件的绝对路径
//
//Basilic Using(重要的引用):
//System.Xml: 该命名空间中封装有对Xml进行操作的常用类,本类中使用了其中的XmlTextReader类
//XmlTextReader: 该类提供对Xml文件进行读取的功能,它可以验证文档是否格式良好,如果不是格式 // 良好的Xml文档,该类在读取过程中将会抛出XmlException异常,可使用该类提供的
// 一些方法对文档节点进行读取,筛选等操作以及得到节点的名称和值
//
//bool XmlTextReader.Read(): 读取流中下一个节点,当读完最后一个节点再次调用该方法该方法返回false
//XmlNodeType XmlTextReader.NodeType: 该属性返回当前节点的类型
// XmlNodeType.Element 元素节点
// XmlNodeType.EndElement 结尾元素节点
// XmlNodeType.XmlDeclaration 文档的第一个节点
// XmlNodeType.Text 文本节点
//bool XmlTextReader.HasAttributes: 当前节点有没有属性,返回true或false
//string XmlTextReader.Name: 返回当前节点的名称
//string XmlTextReader.Value: 返回当前节点的值
//string XmlTextReader.LocalName: 返回当前节点的本地名称
//string XmlTextReader.NamespaceURI: 返回当前节点的命名空间URI
//string XmlTextReader.Prefix: 返回当前节点的前缀
//bool XmlTextReader.MoveToNextAttribute(): 移动到当前节点的下一个属性
//---------------------------------------------------------------------------------------------------

using System;
using System.Xml;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections;

{


    /// <summary>
    /// Xml文件读取器
    /// </summary>

    public class MyXmlReader : IDisposable
    {
        private string _xmlPath;
        private const string _errMsg = "Error Occurred While Reading ";
        private ListBox _listBox;
        private XmlTextReader xmlTxtRd;

        #region XmlReader 的构造器

        public MyXmlReader()
        {
            this._xmlPath = string.Empty;
            this._listBox = null;
            this.xmlTxtRd = null;
        }

        /// <summary>
        /// 构造器
        /// </summary>
        /// <param name="_xmlPath">xml文件绝对路径</param>
        /// <param name="_listBox">列表框用于显示xml</param>

        public MyXmlReader(string _xmlPath, ListBox _listBox)
        {
            this._xmlPath = _xmlPath;
            this._listBox = _listBox;
            this.xmlTxtRd = null;
        }

        #endregion
        #region XmlReader 的资源释放方法

        /// <summary>
        /// 清理该对象所有正在使用的资源

        /// </summary>

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// 释放该对象的实例变量
        /// </summary>
        /// <param name="disposing"></param>

        protected virtual void Dispose(bool disposing)
        {
            if (!disposing)
                return;
            if (this.xmlTxtRd != null)
            {
                this.xmlTxtRd.Close();
                this.xmlTxtRd = null;
            }

            if (this._xmlPath != null)
            {
                this._xmlPath = null;
            }
        }

        #endregion
        #region XmlReader 的属性

        /// <summary>
        /// 获取或设置列表框用于显示xml
        /// </summary>

        public ListBox listBox
        {
            get
            {
                return this._listBox;
            }
            set
            {
                this._listBox = value;
            }
        }

        /// <summary>
        /// 获取或设置xml文件的绝对路径
        /// </summary>

        public string xmlPath
        {
            get
            {
                return this._xmlPath;
            }
            set
            {
                this._xmlPath = value;
            }
        }

        #endregion

        /// <summary>
        /// 遍历Xml文件
        /// </summary>

        public void EachXml()
        {
            this._listBox.Items.Clear();
            this.xmlTxtRd = new XmlTextReader(this._xmlPath);

            try
            {
                while (xmlTxtRd.Read())
                {
                    this._listBox.Items.Add(this.xmlTxtRd.Value);
                }
            }
            catch (XmlException exp)
            {
                throw new XmlException(_errMsg + this._xmlPath + exp.ToString());
            }
            finally
            {
                if (this.xmlTxtRd != null)
                    this.xmlTxtRd.Close();
            }
        }

        /// <summary>
        /// 读取Xml文件的节点类型
        /// </summary>

        public void ReadXmlByNodeType()
        {
            this._listBox.Items.Clear();
            this.xmlTxtRd = new XmlTextReader(this._xmlPath);

            try
            {
                while (xmlTxtRd.Read())
                {
                    this._listBox.Items.Add(this.xmlTxtRd.NodeType.ToString());
                }
            }
            catch (XmlException exp)
            {
                throw new XmlException(_errMsg + this._xmlPath + exp.ToString());
            }
            finally
            {
                if (this.xmlTxtRd != null)
                    this.xmlTxtRd.Close();
            }
        }

        /// <summary>
        /// 根据节点类型过滤Xml文档
        /// </summary>
        /// <param name="xmlNType">XmlNodeType 节点类型的数组</param>

        public void FilterByNodeType(XmlNodeType[] xmlNType)
        {

            this.xmlTxtRd = new XmlTextReader(this._xmlPath);
            try
            {
                while (xmlTxtRd.Read())
                {
                    for (int i = 0; i < xmlNType.Length; i++)
                    {
                        if (xmlTxtRd.NodeType == xmlNType[i])
                        {
                            this._listBox.Items.Add(xmlTxtRd.Name + " is Type " + xmlTxtRd.NodeType.ToString());
                        }
                    }
                }
            }
            catch (XmlException exp)
            {
                throw new XmlException(_errMsg + this.xmlPath + exp.ToString());
            }
            finally
            {
                if (this.xmlTxtRd != null)
                    this.xmlTxtRd.Close();
            }
        }

        /// <summary>
        /// 根据节点类型过滤Xml文档
        /// </summary>
        /// <param name="xmlNType">XmlNodeType 节点类型的数组</param>

        public void FilterByNodeType(XmlNodeType[] xmlNType, Hashtable constantsTable)
        {

            this.xmlTxtRd = new XmlTextReader(this._xmlPath);
            string options_name = "";
            try
            {
                while (xmlTxtRd.Read())
                {
                    for (int i = 0; i < xmlNType.Length; i++)
                    {
                        if (xmlTxtRd.NodeType == xmlNType[i])
                        {
                            if (xmlTxtRd.NodeType == System.Xml.XmlNodeType.Element && xmlTxtRd.Name.Equals("constant"))
                            {
                                if (xmlTxtRd.HasAttributes)
                                {
                                    while (xmlTxtRd.MoveToNextAttribute())
                                    {
                                        if (xmlTxtRd.Name.Equals("name"))
                                            options_name = xmlTxtRd.Value;
                                        if (options_name.Equals("train_state"))
                                            Console.WriteLine(options_name);
                                        //attAndEle = attAndEle + string.Format("{0}='{1}' ",xmlTxtRd.Name,xmlTxtRd.Value);
                                    }
                                }

                            }

                            string opt_txt = "";
                            string opt_value = "";
                            if (xmlTxtRd.NodeType == System.Xml.XmlNodeType.Element && xmlTxtRd.Name.Equals("option"))
                            {
                                if (xmlTxtRd.HasAttributes)
                                {

                                    while (xmlTxtRd.MoveToNextAttribute())
                                    {
                                        //options_name=xmlTxtRd.Value;
                                        if (xmlTxtRd.Name.Equals("text"))
                                            opt_txt = xmlTxtRd.Value;
                                        if (xmlTxtRd.Name.Equals("value"))
                                        {
                                            opt_value = xmlTxtRd.Value;

                                        }

                                    }
                                }
                                constantsTable.Add(options_name + "_" + opt_value, opt_txt);
                            }

                        }
                    }
                }
            }
            catch (XmlException exp)
            {
                throw new XmlException(_errMsg + this.xmlPath + exp.ToString());
            }
            finally
            {
                if (this.xmlTxtRd != null)
                    this.xmlTxtRd.Close();
            }
        }
        /// <summary>
        /// 读取Xml文件的所有文本节点值

        /// </summary>

        public void ReadXmlTextValue()
        {
            this._listBox.Items.Clear();
            this.xmlTxtRd = new XmlTextReader(this._xmlPath);

            try
            {
                while (xmlTxtRd.Read())
                {
                    if (xmlTxtRd.NodeType == XmlNodeType.Text)
                    {
                        this._listBox.Items.Add(xmlTxtRd.Value);
                    }
                }
            }
            catch (XmlException xmlExp)
            {
                throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString());
            }
            finally
            {
                if (this.xmlTxtRd != null)
                    this.xmlTxtRd.Close();
            }
        }

        /// <summary>
        /// 读取Xml文件的属性
        /// </summary>

        public void ReadXmlAttributes()
        {
            this._listBox.Items.Clear();
            this.xmlTxtRd = new XmlTextReader(this._xmlPath);

            try
            {
                while (xmlTxtRd.Read())
                {
                    if (xmlTxtRd.NodeType == XmlNodeType.Element)
                    {
                        if (xmlTxtRd.HasAttributes)
                        {
                            this._listBox.Items.Add("The Element " + xmlTxtRd.Name + " has " + xmlTxtRd.AttributeCount + " Attributes");

                            this._listBox.Items.Add("The Attributes are:");

                            while (xmlTxtRd.MoveToNextAttribute())
                            {
                                this._listBox.Items.Add(xmlTxtRd.Name + " = " + xmlTxtRd.Value);
                            }
                        }
                        else
                        {
                            this._listBox.Items.Add("The Element " + xmlTxtRd.Name + " has no Attribute");
                        }
                        this._listBox.Items.Add("");
                    }
                }
            }
            catch (XmlException xmlExp)
            {
                throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString());
            }
            finally
            {
                if (this.xmlTxtRd != null)
                    this.xmlTxtRd.Close();
            }
        }

        /// <summary>
        /// 读取Xml文件的命名空间
        /// </summary>

        public void ReadXmlNamespace()
        {
            this._listBox.Items.Clear();
            this.xmlTxtRd = new XmlTextReader(this._xmlPath);
            try
            {
                while (xmlTxtRd.Read())
                {
                    if (xmlTxtRd.NodeType == XmlNodeType.Element && xmlTxtRd.Prefix != "")
                    {
                        this._listBox.Items.Add("The Prefix " + xmlTxtRd.Prefix + " is associated with namespace " + xmlTxtRd.NamespaceURI);

                        this._listBox.Items.Add("The Element with the local name " + xmlTxtRd.LocalName + " is associated with" + " the namespace " + xmlTxtRd.NamespaceURI);
                    }

                    if (xmlTxtRd.NodeType == XmlNodeType.Element && xmlTxtRd.HasAttributes)
                    {
                        while (xmlTxtRd.MoveToNextAttribute())
                        {
                            if (xmlTxtRd.Prefix != "")
                            {
                                this._listBox.Items.Add("The Prefix " + xmlTxtRd.Prefix + " is associated with namespace " + xmlTxtRd.NamespaceURI);

                                this._listBox.Items.Add("The Attribute with the local name " + xmlTxtRd.LocalName + " is associated with the namespace " + xmlTxtRd.NamespaceURI);

                            }
                        }
                    }
                }
            }
            catch (XmlException xmlExp)
            {
                throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString());
            }
            finally
            {
                if (this.xmlTxtRd != null)
                    this.xmlTxtRd.Close();
            }
        }

        /// <summary>
        /// 读取整个Xml文件
        /// </summary>

        public void ReadXml()
        {
            string attAndEle = string.Empty;
            this._listBox.Items.Clear();
            this.xmlTxtRd = new XmlTextReader(this._xmlPath);

            try
            {
                while (xmlTxtRd.Read())
                {
                    if (xmlTxtRd.NodeType == XmlNodeType.XmlDeclaration)
                        this._listBox.Items.Add(string.Format("<?{0} {1} ?>", xmlTxtRd.Name, xmlTxtRd.Value));
                    else if (xmlTxtRd.NodeType == XmlNodeType.Element)
                    {
                        attAndEle = string.Format("<{0} ", xmlTxtRd.Name);
                        if (xmlTxtRd.HasAttributes)
                        {
                            while (xmlTxtRd.MoveToNextAttribute())
                            {
                                attAndEle = attAndEle + string.Format("{0}='{1}' ", xmlTxtRd.Name, xmlTxtRd.Value);
                            }
                        }

                        attAndEle = attAndEle.Trim() + ">";
                        this._listBox.Items.Add(attAndEle);
                    }
                    else if (xmlTxtRd.NodeType == XmlNodeType.EndElement)
                        this._listBox.Items.Add(string.Format("</{0}>", xmlTxtRd.Name));
                    else if (xmlTxtRd.NodeType == XmlNodeType.Text)
                        this._listBox.Items.Add(xmlTxtRd.Value);
                }
            }
            catch (XmlException xmlExp)
            {
                throw new XmlException(_errMsg + this._xmlPath + xmlExp.ToString());
            }
            finally
            {
                if (this.xmlTxtRd != null)
                    this.xmlTxtRd.Close();
            }
        }
    }
}
原文:http://blog.5d.cn/user1/pineapple/200708/427657.html

转载于:https://www.cnblogs.com/atck/archive/2009/08/11/1543302.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值