Ejemplo n.º 1
0
 /// <summary>
 ///     修改数据
 /// </summary>
 /// <param name="path">路径</param>
 /// <param name="node">节点</param>
 /// <param name="attribute">属性名,非空时修改该节点属性值,否则修改节点值</param>
 /// <param name="value">值</param>
 /// <returns></returns>
 public static void Update(string path, string node, string attribute, string value)
 {
     /**************************************************
      * 使用示列:
      * XmlHelper.Insert(path, "/Node", "", "Value")
      * XmlHelper.Insert(path, "/Node", "Attribute", "Value")
      ************************************************/
     try
     {
         var xmlDocument = new XmlDocument();
         xmlDocument.Load(path);
         var selectSingleNode = xmlDocument.SelectSingleNode(node);
         var xmlElement       = (XmlElement)selectSingleNode;
         if (attribute.Equals(""))
         {
             if (xmlElement != null)
             {
                 xmlElement.InnerText = value;
             }
         }
         else
         {
             xmlElement.SetAttribute(attribute, value);
         }
         xmlDocument.Save(path);
     }
     catch (Exception exception)
     {
         LOGCore.Trace(LOGCore.ST.Day, "【XMLHelper】", exception.ToString());
     }
 }
Ejemplo n.º 2
0
 /// <summary>
 ///     删除数据
 /// </summary>
 /// <param name="path">路径</param>
 /// <param name="node">节点</param>
 /// <param name="attribute">属性名,非空时删除该节点属性值,否则删除节点值</param>
 /// <returns></returns>
 public static void Delete(string path, string node, string attribute)
 {
     /**************************************************
      * 使用示列:
      * XmlHelper.Delete(path, "/Node", "")
      * XmlHelper.Delete(path, "/Node", "Attribute")
      ************************************************/
     try
     {
         var xmlDocument = new XmlDocument();
         xmlDocument.Load(path);
         var selectSingleNode = xmlDocument.SelectSingleNode(node);
         var xmlElement       = (XmlElement)selectSingleNode;
         if (attribute.Equals(""))
         {
             selectSingleNode.ParentNode.RemoveChild(selectSingleNode);
         }
         else
         {
             xmlElement.RemoveAttribute(attribute);
         }
         xmlDocument.Save(path);
     }
     catch (Exception exception)
     {
         LOGCore.Trace(LOGCore.ST.Day, "【XMLHelper】", exception.ToString());
     }
 }
Ejemplo n.º 3
0
 /// <summary>
 ///     读取xml的节点
 /// </summary>
 /// <param name="path">路径</param>
 /// <param name="nodeName">节点名称</param>
 /// <param name="name">属性名称</param>
 /// <returns></returns>
 public static string ReadXml(string path, string nodeName, string name) //读取XML
 {
     try
     {
         var xmlValue = "";
         if (!File.Exists(path))
         {
             return(xmlValue);
         }
         var myFile        = new FileStream(path, FileMode.Open); //打开xml文件
         var xmlTextReader = new XmlTextReader(myFile);           //xml文件阅读器
         while (xmlTextReader.Read())
         {
             if (xmlTextReader.Name == nodeName)
             {
                 //获取服务器的地址//获取升级文档的最后一次更新日期
                 xmlValue = xmlTextReader.GetAttribute(name);
                 break;
             }
         }
         xmlTextReader.Close();
         myFile.Close();
         return(xmlValue);
     }
     catch (Exception exception)
     {
         LOGCore.Trace(LOGCore.ST.Day, "【XMLHelper】", exception.ToString());
         return(null);
     }
 }
Ejemplo n.º 4
0
 /// <summary>
 ///     静态扩展
 /// </summary>
 /// <typeparam name="T">需要序列化的对象类型,必须声明[Serializable]特征</typeparam>
 /// <param name="obj">需要序列化的对象</param>
 /// <param name="omitXmlDeclaration">true:省略XML声明;否则为false.默认false,即编写 XML 声明。</param>
 /// <returns></returns>
 public static string SerializeToXmlStr <T>(T obj, bool omitXmlDeclaration)
 {
     try
     {
         return(Serialize(obj, omitXmlDeclaration));
     }
     catch (Exception exception)
     {
         LOGCore.Trace(LOGCore.ST.Day, "【XMLHelper】", exception.ToString());
         return(null);
     }
 }
Ejemplo n.º 5
0
 /// <summary>
 /// (秒)时间转Int
 /// </summary>
 /// <param name="time"></param>
 /// <returns></returns>
 public static string ConvertToDateTimeStr(DateTime time)
 {
     try
     {
         return(time.ToString("yyyyMMddhhmmss"));
     }
     catch (Exception ex)
     {
         LOGCore.Trace(LOGCore.ST.Day, "【TimeHelper】", ex.ToString());
         return("0");
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// 读取excel ,默认第一行为标头
        /// </summary>
        /// <param name="strFileName"></param>
        /// <param name="fileStream"></param>
        /// <returns></returns>
        public static DataTable Import(string strFileName, Stream fileStream)
        {
            DataTable dt = new DataTable();

            IWorkbook workbook = null;

            try
            {
                if (strFileName.IndexOf(".xlsx") > 0) // 2007版本
                {
                    workbook = new XSSFWorkbook(fileStream);
                }
                else if (strFileName.IndexOf(".xls") > 0) // 2003版本
                {
                    workbook = new HSSFWorkbook(fileStream);
                }
            }
            catch (Exception ex)
            {
                LOGCore.Trace(LOGCore.ST.Day, "【ExcelHelper】", ex.ToString());
                workbook = new HSSFWorkbook(fileStream);
            }
            ISheet sheet = workbook.GetSheetAt(0);

            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

            IRow headerRow = sheet.GetRow(0);
            int  cellCount = headerRow.LastCellNum;

            for (int j = 0; j < cellCount; j++)
            {
                ICell cell = headerRow.GetCell(j);
                dt.Columns.Add(cell.ToString());
            }

            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
            {
                IRow    row     = sheet.GetRow(i);
                DataRow dataRow = dt.NewRow();

                for (int j = row.FirstCellNum; j < cellCount; j++)
                {
                    if (row.GetCell(j) != null)
                    {
                        dataRow[j] = row.GetCell(j).ToString();
                    }
                }

                dt.Rows.Add(dataRow);
            }
            return(dt);
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Excel导出
 /// </summary>
 /// <param name="dt"></param>
 /// <param name="filePath"></param>
 public static void DownloadExcel(DataTable dt, string filePath)
 {
     try
     {
         IWorkbook book = null;
         if (!string.IsNullOrEmpty(filePath) && null != dt && dt.Rows.Count > 0)
         {
             if (filePath.IndexOf(".xlsx") > 0) // 2007版本
             {
                 book = new XSSFWorkbook();
             }
             else if (filePath.IndexOf(".xls") > 0) // 2003版本
             {
                 book = new HSSFWorkbook();
             }
             else
             {
                 filePath += ".xls";
                 book      = new HSSFWorkbook();
             }
             ISheet sheet = book.CreateSheet(dt.TableName);
             IRow   row   = sheet.CreateRow(0);
             for (int i = 0; i < dt.Columns.Count; i++)
             {
                 row.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
             }
             for (int i = 0; i < dt.Rows.Count; i++)
             {
                 IRow row2 = sheet.CreateRow(i + 1);
                 for (int j = 0; j < dt.Columns.Count; j++)
                 {
                     row2.CreateCell(j).SetCellValue(Convert.ToString(dt.Rows[i][j]));
                 }
             }
             using (MemoryStream ms = new MemoryStream())
             {
                 book.Write(ms);
                 using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                 {
                     byte[] data = ms.ToArray();
                     fs.Write(data, 0, data.Length);
                     fs.Flush();
                 }
                 book = null;
             }
         }
     }
     catch (Exception ex)
     {
         LOGCore.Trace(LOGCore.ST.Day, "ExcelHelper", ex.ToString());
     }
 }
Ejemplo n.º 8
0
 /// <summary>
 ///     将DataTable以指定的根结点名称写入文件
 /// </summary>
 /// <param name="dataTable">含有数据的DataTable</param>
 /// <param name="rootName">根结点名称</param>
 /// <param name="filePath">文件路径</param>
 public static void SaveTableToFile(DataTable dataTable, string rootName, string filePath)
 {
     try
     {
         var dataSet = new DataSet(rootName);
         dataSet.Tables.Add(dataTable.Copy());
         dataSet.WriteXml(filePath);
     }
     catch (Exception exception)
     {
         LOGCore.Trace(LOGCore.ST.Day, "【XMLHelper】", exception.ToString());
     }
 }
Ejemplo n.º 9
0
 /// <summary>
 ///     读取xml文件,并将文件序列化为类
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="path"></param>
 /// <returns></returns>
 public static T ReadXML <T>(string path)
 {
     try
     {
         var reader = new XmlSerializer(typeof(T));
         var file   = new StreamReader(path);
         return((T)reader.Deserialize(file));
     }
     catch (Exception exception)
     {
         LOGCore.Trace(LOGCore.ST.Day, "【XMLHelper】", exception.ToString());
         return(default(T));
     }
 }
Ejemplo n.º 10
0
 /// <summary>
 ///     获取一个字符串xml文档中的dataSet
 /// </summary>
 /// <param name="xmlString">含有xml信息的字符串</param>
 /// <param name="dataSet"></param>
 public static void GetXmlValueDataSet(string xmlString, ref DataSet dataSet)
 {
     try
     {
         var xmlDocument = new XmlDocument();
         xmlDocument.LoadXml(xmlString);
         var xmlNodeReader = new XmlNodeReader(xmlDocument);
         dataSet.ReadXml(xmlNodeReader);
         xmlNodeReader.Close();
     }
     catch (Exception exception)
     {
         LOGCore.Trace(LOGCore.ST.Day, "【XMLHelper】", exception.ToString());
     }
 }
Ejemplo n.º 11
0
        public static string HttpGetHTML(string uri, System.Text.Encoding code, System.Net.CookieContainer cotainer)
        {
            if (uri == null || (uri.ToLower().IndexOf("http://") == -1 && uri.ToLower().IndexOf("https://") == -1))
            {
                return("");
            }
            StreamReader sr = null;

            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
                request.Headers.Add("UA-CPU", "x86");
                request.Referer         = uri;
                request.UserAgent       = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727;)";
                request.KeepAlive       = false;
                request.CookieContainer = cotainer;
                request.Timeout         = 8000; //设置远程页面请求超时时间


                HttpWebResponse myResponse = (HttpWebResponse)request.GetResponse();
                if (myResponse.StatusCode == HttpStatusCode.OK)
                {
                    sr = new StreamReader(myResponse.GetResponseStream(), code);
                    string serverResponse = sr.ReadToEnd().Trim();
                    return(serverResponse);
                }
                else
                {
                    //return "失败:Status:" + myResponse.StatusCode.ToString();
                    return(string.Empty);
                }
            }
            catch (Exception ex)
            {
                LOGCore.Trace(LOGCore.ST.Day, "【HttpHelper】", ex.ToString());
                return(string.Empty);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                    sr.Dispose();
                }
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        ///     将对象写入XML文件
        /// </summary>
        /// <typeparam name="T">C#对象名</typeparam>
        /// <param name="item">对象实例</param>
        /// <param name="path">路径</param>
        /// <param name="jjdbh">标号</param>
        /// <param name="ends">结束符号(整个xml的路径类似如下:C:\xmltest\201111send.xml,其中path=C:\xmltest,jjdbh=201111,ends=send)</param>
        /// <returns></returns>
        public static string WriteXML <T>(T item, string path, string jjdbh, string ends)
        {
            if (string.IsNullOrEmpty(ends))
            {
                ends = "send";
            }
            var i          = 0; //控制写入文件的次数,
            var serializer = new XmlSerializer(item.GetType());

            object[] obj     = { path, "\\", jjdbh, ends, ".xml" };
            var      xmlPath = string.Concat(obj);

            while (true)
            {
                try
                {
                    var fileStream = File.Create(xmlPath); //用filestream方式创建文件不会出现“文件正在占用中,用File.create”则不行
                    fileStream.Close();
                    TextWriter writer = new StreamWriter(xmlPath, false, Encoding.UTF8);
                    var        xmlSerializerNamespaces = new XmlSerializerNamespaces();
                    xmlSerializerNamespaces.Add(string.Empty, string.Empty);
                    serializer.Serialize(writer, item, xmlSerializerNamespaces);
                    writer.Flush();
                    writer.Close();
                    break;
                }
                catch (Exception exception)
                {
                    if (i < 5)
                    {
                        i++;
                    }
                    else
                    {
                        LOGCore.Trace(LOGCore.ST.Day, "【XMLHelper】", exception.ToString());
                        break;
                    }
                }
            }
            return(SerializeToXmlStr(item, true));
        }
Ejemplo n.º 13
0
 /// <summary>
 ///     获得xml文件中指定节点的节点数据
 /// </summary>
 /// <returns></returns>
 public static string GetNodeInfoByNodeName(string path, string nodeName)
 {
     try
     {
         var xmlString   = "";
         var xmlDocument = new XmlDocument();
         xmlDocument.Load(path);
         var documentElementRoot = xmlDocument.DocumentElement;
         var selectSingleNode    = documentElementRoot.SelectSingleNode("//" + nodeName);
         if (selectSingleNode != null)
         {
             xmlString = selectSingleNode.InnerText;
         }
         return(xmlString);
     }
     catch (Exception exception)
     {
         LOGCore.Trace(LOGCore.ST.Day, "【XMLHelper】", exception.ToString());
         return(null);
     }
 }
Ejemplo n.º 14
0
 public static string HttpPost(string url, string data, System.Text.Encoding encoding)
 {
     try
     {
         byte[]         bData  = encoding.GetBytes(data);
         HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
         WebReq.Method        = "POST";
         WebReq.ContentType   = "application/x-www-form-urlencoded";
         WebReq.ContentLength = bData.Length;
         Stream PostData = WebReq.GetRequestStream();
         PostData.Write(bData, 0, bData.Length);
         PostData.Close();
         HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
         Stream          Answer  = WebResp.GetResponseStream();
         return(getResult(Answer, encoding));
     }
     catch (System.Exception ex)
     {
         LOGCore.Trace(LOGCore.ST.Day, "【HttpPost】", ex.ToString());
         return(null);
     }
 }
Ejemplo n.º 15
0
        /// <summary>
        ///     读取数据
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="node">节点</param>
        /// <param name="attribute">属性名,非空时返回该属性值,否则返回串联值</param>
        /// <returns>string</returns>
        public static string Read(string path, string node, string attribute)
        {
            /**************************************************
             * 使用示列:
             * XmlHelper.Read(path, "/Node", "")
             * XmlHelper.Read(path, "/Node/Element[@Attribute='Name']", "Attribute")
             ************************************************/
            var value = "";

            try
            {
                var xmlDocument = new XmlDocument();
                xmlDocument.Load(path);
                var selectSingleNode = xmlDocument.SelectSingleNode(node);
                value = attribute.Equals("")? selectSingleNode.InnerText: selectSingleNode.Attributes[attribute].Value;
            }
            catch (Exception exception)
            {
                LOGCore.Trace(LOGCore.ST.Day, "【XMLHelper】", exception.ToString());
            }
            return(value);
        }
Ejemplo n.º 16
0
        /// <summary>
        ///     创建XML文档
        /// </summary>
        /// <param name="name">根节点名称</param>
        /// <param name="type">根节点的一个属性值</param>
        /// <returns></returns>
        public static XmlDocument CreateXmlDocument(string name, string type)
        {
            /**************************************************
             * .net中调用方法:写入文件中,则:
             * document = XmlOperate.CreateXmlDocument("sex", "sexy");
             * document.Save("c:/bookstore.xml");
             ************************************************/
            XmlDocument xmlDocument;

            try
            {
                xmlDocument = new XmlDocument();
                xmlDocument.LoadXml("<" + name + "/>");
                var rootElement = xmlDocument.DocumentElement;
                rootElement.SetAttribute("type", type);
            }
            catch (Exception exception)
            {
                LOGCore.Trace(LOGCore.ST.Day, "【XMLHelper】", exception.ToString());
                return(null);
            }
            return(xmlDocument);
        }
Ejemplo n.º 17
0
 /// <summary>
 ///     读取XML资源到DataSet中
 /// </summary>
 /// <param name="source">XML资源,文件为路径,否则为XML字符串</param>
 /// <param name="xmlType">XML资源类型</param>
 /// <returns>DataSet</returns>
 public static DataSet GetDataSet(string source, XmlType xmlType)
 {
     try
     {
         var dataSet = new DataSet();
         if (xmlType == XmlType.File)
         {
             dataSet.ReadXml(source);
         }
         else
         {
             var xmlDocument = new XmlDocument();
             xmlDocument.LoadXml(source);
             var xmlNodeReader = new XmlNodeReader(xmlDocument);
             dataSet.ReadXml(xmlNodeReader);
         }
         return(dataSet);
     }
     catch (Exception exception)
     {
         LOGCore.Trace(LOGCore.ST.Day, "【XMLHelper】", exception.ToString());
         return(null);
     }
 }
Ejemplo n.º 18
0
 /// <summary>
 ///     读取XML资源中指定的DataTable的指定行指定列的值
 /// </summary>
 /// <param name="source">XML资源</param>
 /// <param name="xmlType">XML资源类型:文件,字符串</param>
 /// <param name="tableName">表名</param>
 /// <param name="rowIndex">行号</param>
 /// <param name="colIndex">列号</param>
 /// <returns>值,不存在时返回Null</returns>
 public static object GetTableCell(string source, XmlType xmlType, string tableName, int rowIndex, int colIndex)
 {
     try
     {
         var dataSet = new DataSet();
         if (xmlType == XmlType.File)
         {
             dataSet.ReadXml(source);
         }
         else
         {
             var xmlDocument = new XmlDocument();
             xmlDocument.LoadXml(source);
             var xmlNodeReader = new XmlNodeReader(xmlDocument);
             dataSet.ReadXml(xmlNodeReader);
         }
         return(dataSet.Tables[tableName].Rows[rowIndex][colIndex]);
     }
     catch (Exception exception)
     {
         LOGCore.Trace(LOGCore.ST.Day, "【XMLHelper】", exception.ToString());
         return(null);
     }
 }
Ejemplo n.º 19
0
        /// <summary>
        /// post
        /// </summary>
        /// <param name="url">POST请求的地址</param>
        /// <param name="paramList">参数列表 例如 name=zhangsan&pass=lisi</param>
        /// <param name="referer">来源地址</param>
        /// <returns></returns>
        public static string Post(String url, String paramList, string referer)
        {
            HttpWebResponse res       = null;
            HttpWebRequest  req       = null;
            string          strResult = "";

            try
            {
                req = (HttpWebRequest)WebRequest.Create(url);
                //配置请求header
                req.Headers.Add(HttpRequestHeader.AcceptCharset, "GBK,utf-8;q=0.7,*;q=0.3");
                req.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate,sdch");
                req.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.8");
                req.Accept    = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
                req.KeepAlive = true;
                req.Referer   = referer;
                req.Headers.Add(HttpRequestHeader.CacheControl, "max-age=0");
                req.UserAgent         = "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.5 Safari/534.7";
                req.Method            = "POST";
                req.ContentType       = "application/x-www-form-urlencoded";
                req.AllowAutoRedirect = true;
                StringBuilder UrlEncoded = new StringBuilder();
                //对参数进行encode
                Char[] reserved  = { '?', '=', '&' };
                byte[] SomeBytes = null;
                if (paramList != null)
                {
                    int i = 0, j;
                    while (i < paramList.Length)
                    {
                        j = paramList.IndexOfAny(reserved, i);
                        if (j == -1)
                        {
                            UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, paramList.Length - i)));
                            break;
                        }
                        UrlEncoded.Append(HttpUtility.UrlEncode(paramList.Substring(i, j - i)));
                        UrlEncoded.Append(paramList.Substring(j, 1));
                        i = j + 1;
                    }
                    SomeBytes         = Encoding.UTF8.GetBytes(UrlEncoded.ToString());
                    req.ContentLength = SomeBytes.Length;
                    Stream newStream = req.GetRequestStream();
                    newStream.Write(SomeBytes, 0, SomeBytes.Length);
                    newStream.Close();
                }
                else
                {
                    req.ContentLength = 0;
                }
                //返回请求
                res = (HttpWebResponse)req.GetResponse();
                Encoding encode         = System.Text.Encoding.GetEncoding("utf-8");
                Stream   responseStream = null;
                if (res.ContentEncoding.ToLower() == "gzip")
                {
                    responseStream = new System.IO.Compression.GZipStream(res.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                }
                else if (res.ContentEncoding.ToLower() == "deflate")
                {
                    responseStream = new System.IO.Compression.DeflateStream(res.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                }
                else
                {
                    responseStream = res.GetResponseStream();
                }
                StreamReader sr = new StreamReader(responseStream, encode);
                strResult = sr.ReadToEnd();
            }
            catch (Exception ex)
            {
                LOGCore.Trace(LOGCore.ST.Day, "【HttpHelper】", ex.ToString());
            }
            finally
            {
                res.Close();
            }
            return(strResult);
        }