C#文件操作类分享

本文实例为大家分享了C#文件操作类的具体代码,供大家参考,具体内容如下

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;
using System.Collections;
using System.Data.Common;

namespace DotNet.Utilities
{
 //JSON转换类
 public class ConvertJson
 {
 #region 私有方法
 /// <summary>
 /// 过滤特殊字符
 /// </summary>
 private static string String2Json(String s)
 {
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < s.Length; i++)
  {
  char c = s.ToCharArray()[i];
  switch (c)
  {
   case '\"':
   sb.Append("\\\""); break;
   case '\\':
   sb.Append("\\\\"); break;
   case '/':
   sb.Append("\\/"); break;
   case '\b':
   sb.Append("\\b"); break;
   case '\f':
   sb.Append("\\f"); break;
   case '\n':
   sb.Append("\\n"); break;
   case '\r':
   sb.Append("\\r"); break;
   case '\t':
   sb.Append("\\t"); break;
   default:
   sb.Append(c); break;
  }
  }
  return sb.ToString();
 }

 /// <summary>
 /// 格式化字符型、日期型、布尔型
 /// </summary>
 private static string StringFormat(string str, Type type)
 {
  if (type == typeof(string))
  {
  str = String2Json(str);
  str = "\"" + str + "\"";
  }
  else if (type == typeof(DateTime))
  {
  str = "\"" + str + "\"";
  }
  else if (type == typeof(bool))
  {
  str = str.ToLower();
  }
  else if (type != typeof(string) && string.IsNullOrEmpty(str))
  {
  str = "\"" + str + "\"";
  }
  return str;
 }
 #endregion

 #region List转换成Json
 /// <summary>
 /// List转换成Json
 /// </summary>
 public static string ListToJson<T>(IList<T> list)
 {
  object obj = list[0];
  return ListToJson<T>(list, obj.GetType().Name);
 }

 /// <summary>
 /// List转换成Json
 /// </summary>
 public static string ListToJson<T>(IList<T> list, string jsonName)
 {
  StringBuilder Json = new StringBuilder();
  if (string.IsNullOrEmpty(jsonName)) jsonName = list[0].GetType().Name;
  Json.Append("{\"" + jsonName + "\":[");
  if (list.Count > 0)
  {
  for (int i = 0; i < list.Count; i++)
  {
   T obj = Activator.CreateInstance<T>();
   PropertyInfo[] pi = obj.GetType().GetProperties();
   Json.Append("{");
   for (int j = 0; j < pi.Length; j++)
   {
   Type type = pi[j].GetValue(list[i], null).GetType();
   Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));

   if (j < pi.Length - 1)
   {
    Json.Append(",");
   }
   }
   Json.Append("}");
   if (i < list.Count - 1)
   {
   Json.Append(",");
   }
  }
  }
  Json.Append("]}");
  return Json.ToString();
 }
 #endregion

 #region 对象转换为Json
 /// <summary>
 /// 对象转换为Json
 /// </summary>
 /// <param name="jsonObject">对象</param>
 /// <returns>Json字符串</returns>
 public static string ToJson(object jsonObject)
 {
  string jsonString = "{";
  PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
  for (int i = 0; i < propertyInfo.Length; i++)
  {
  object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
  string value = string.Empty;
  if (objectValue is DateTime || objectValue is Guid || objectValue is TimeSpan)
  {
   value = "'" + objectValue.ToString() + "'";
  }
  else if (objectValue is string)
  {
   value = "'" + ToJson(objectValue.ToString()) + "'";
  }
  else if (objectValue is IEnumerable)
  {
   value = ToJson((IEnumerable)objectValue);
  }
  else
  {
   value = ToJson(objectValue.ToString());
  }
  jsonString += "\"" + ToJson(propertyInfo[i].Name) + "\":" + value + ",";
  }
  jsonString.Remove(jsonString.Length - 1, jsonString.Length);
  return jsonString + "}";
 }
 #endregion

 #region 对象集合转换Json
 /// <summary>
 /// 对象集合转换Json
 /// </summary>
 /// <param name="array">集合对象</param>
 /// <returns>Json字符串</returns>
 public static string ToJson(IEnumerable array)
 {
  string jsonString = "[";
  foreach (object item in array)
  {
  jsonString += ToJson(item) + ",";
  }
  jsonString.Remove(jsonString.Length - 1, jsonString.Length);
  return jsonString + "]";
 }
 #endregion

 #region 普通集合转换Json
 /// <summary>
 /// 普通集合转换Json
 /// </summary>
 /// <param name="array">集合对象</param>
 /// <returns>Json字符串</returns>
 public static string ToArrayString(IEnumerable array)
 {
  string jsonString = "[";
  foreach (object item in array)
  {
  jsonString = ToJson(item.ToString()) + ",";
  }
  jsonString.Remove(jsonString.Length - 1, jsonString.Length);
  return jsonString + "]";
 }
 #endregion

 #region DataSet转换为Json
 /// <summary>
 /// DataSet转换为Json
 /// </summary>
 /// <param name="dataSet">DataSet对象</param>
 /// <returns>Json字符串</returns>
 public static string ToJson(DataSet dataSet)
 {
  string jsonString = "{";
  foreach (DataTable table in dataSet.Tables)
  {
  jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
  }
  jsonString = jsonString.TrimEnd(',');
  return jsonString + "}";
 }
 #endregion

 #region Datatable转换为Json
 /// <summary>
 /// Datatable转换为Json
 /// </summary>
 /// <param name="table">Datatable对象</param>
 /// <returns>Json字符串</returns>
 public static string ToJson(DataTable dt)
 {
  StringBuilder jsonString = new StringBuilder();
  jsonString.Append("[");
  DataRowCollection drc = dt.Rows;
  for (int i = 0; i < drc.Count; i++)
  {
  jsonString.Append("{");
  for (int j = 0; j < dt.Columns.Count; j++)
  {
   string strKey = dt.Columns[j].ColumnName;
   string strValue = drc[i][j].ToString();
   Type type = dt.Columns[j].DataType;
   jsonString.Append("\"" + strKey + "\":");
   strValue = StringFormat(strValue, type);
   if (j < dt.Columns.Count - 1)
   {
   jsonString.Append(strValue + ",");
   }
   else
   {
   jsonString.Append(strValue);
   }
  }
  jsonString.Append("},");
  }
  jsonString.Remove(jsonString.Length - 1, 1);
  jsonString.Append("]");
  return jsonString.ToString();
 }

 /// <summary>
 /// DataTable转换为Json
 /// </summary>
 public static string ToJson(DataTable dt, string jsonName)
 {
  StringBuilder Json = new StringBuilder();
  if (string.IsNullOrEmpty(jsonName)) jsonName = dt.TableName;
  Json.Append("{\"" + jsonName + "\":[");
  if (dt.Rows.Count > 0)
  {
  for (int i = 0; i < dt.Rows.Count; i++)
  {
   Json.Append("{");
   for (int j = 0; j < dt.Columns.Count; j++)
   {
   Type type = dt.Rows[i][j].GetType();
   Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
   if (j < dt.Columns.Count - 1)
   {
    Json.Append(",");
   }
   }
   Json.Append("}");
   if (i < dt.Rows.Count - 1)
   {
   Json.Append(",");
   }
  }
  }
  Json.Append("]}");
  return Json.ToString();
 }
 #endregion

 #region DataReader转换为Json
 /// <summary>
 /// DataReader转换为Json
 /// </summary>
 /// <param name="dataReader">DataReader对象</param>
 /// <returns>Json字符串</returns>
 public static string ToJson(DbDataReader dataReader)
 {
  StringBuilder jsonString = new StringBuilder();
  jsonString.Append("[");
  while (dataReader.Read())
  {
  jsonString.Append("{");
  for (int i = 0; i < dataReader.FieldCount; i++)
  {
   Type type = dataReader.GetFieldType(i);
   string strKey = dataReader.GetName(i);
   string strValue = dataReader[i].ToString();
   jsonString.Append("\"" + strKey + "\":");
   strValue = StringFormat(strValue, type);
   if (i < dataReader.FieldCount - 1)
   {
   jsonString.Append(strValue + ",");
   }
   else
   {
   jsonString.Append(strValue);
   }
  }
  jsonString.Append("},");
  }
  dataReader.Close();
  jsonString.Remove(jsonString.Length - 1, 1);
  jsonString.Append("]");
  return jsonString.ToString();
 }
 #endregion
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • C#常用目录文件操作类实例

    本文实例讲述了C#常用目录文件操作类.分享给大家供大家参考.具体分析如下: 这个c#类封装了常用的目录操作,包括列出目录下的文件.检测目录是否存在.得到目录下的文件列表.检测目录是否为空.查找目录下的文件等等功能 using System; using System.Text; using System.IO; namespace DotNet.Utilities { /// <summary> /// 文件操作夹 /// </summary> public static clas

  • C#封装的常用文件操作类实例

    本文实例讲述了C#封装的常用文件操作类.分享给大家供大家参考.具体如下: 这个C#类封装了我们经常能用到的文件操作方法,包括读写文件.获取文件扩展名.复制文件.追加内容到文件.删除文件.移动文件.创建目录.递归删除文件及目录.列目录.列文件等,不可多得. using System; using System.Text; using System.Web; using System.IO; namespace DotNet.Utilities { public class FileOperate

  • C#使用iTextSharp封装的PDF文件操作类实例

    本文实例讲述了C#使用iTextSharp封装的PDF文件操作类.分享给大家供大家参考.具体分析如下: 这个C#代码主要讲iTextSharp中用于操作PDF文件的方法进行了再次封装,可以更加方便的访问PDF文档,可以动态生成PDF文件.添加内容.设置段落.设置字体等. using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; namespace DotNet.Utilities { /// <summary> ///

  • C#实现的Excel文件操作类实例

    本文实例讲述了C#实现的Excel文件操作类.分享给大家供大家参考,具体如下: using System; using System.Data; using System.Data.OleDb; using System.Text; using System.IO; namespace Hxh.API { /// <summary> /// ExcelOpration 的摘要说明. /// </summary> public class ExcelOpration { OleDbC

  • C#配置文件操作类分享

    C#配置文件操作类,供大家参考,具体内容如下 注意添加引用:System.Configuration: using System; using System.Collections.Generic; using System.Text; using System.Configuration; namespace DotNet.Utilities.配置文件操作类 { public class ConfigHelper_sufei { /// <summary> /// 根据Key取Value值

  • C#文件操作类分享

    本文实例为大家分享了C#文件操作类的具体代码,供大家参考,具体内容如下 using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Reflection; using System.Collections; using System.Data.Common; namespace DotNet.Utilities { //JSON转换类 public class

  • Python实现的ini文件操作类分享

    类代码: # -*- coding:gbk -*- import ConfigParser, os class INIFILE: def __init__(self, filename): self.filename = filename self.initflag = False self.cfg = None self.readhandle = None self.writehandle = None def Init(self): self.cfg = ConfigParser.Confi

  • Python实现的tab文件操作类分享

    类代码: # -*- coding:gbk -*- import os class TABFILE: def __init__(self, filename, dest_file = None): self.filename = filename if not dest_file: self.dest_file = filename else: self.dest_file = dest_file self.filehandle = None self.content = [] self.ini

  • PHP实现的文件操作类及文件下载功能示例

    本文实例讲述了PHP实现的文件操作类及文件下载功能.分享给大家供大家参考,具体如下: 文件操作类: <?php // Copyright 2005, Lee Babin (lee@thecodeshoppe.com) // This code may be used and redistributed without charge // under the terms of the GNU General Public // License version 2.0 or later -- www

  • python写日志文件操作类与应用示例

    本文实例讲述了python写日志文件操作类与应用.分享给大家供大家参考,具体如下: 项目的开发过程中,日志文件是少不了的,通过写日志文件,可以知道程序运行的情况.特别当部署在生产环境中的时候,这个时候一般不能debug , 当然在有些情况时可以 remote debug (远程debug).那种情况另当别论.还是用通常的写日志的方法,比如在 java 中,经常可以看到 log4j,sf4j,logback等三方组件来写日志. 在python中如何实现呢,其实python 本身也带了日志操作的库.

  • Python文件操作类操作实例详解

    本文讲述了Python文件操作类的操作实例,详细代码如下: #!/usr/bin/env python #!/usr/bin/env python #coding:utf-8 # Purpose: 文件操作类 #声明一个字符串文本 poem=''' Programming is fun测试 When the work is done if you wanna make your work also fun: use Python! ''' #创建一个file类的实例,模式可以为:只读模式('r'

随机推荐