.NET技术-常规操作

.NET技术-常规操作

 

一、 基础操作

 Linq 中按照多个值进行分组(GroupBy)

 Linq 中按照多个值进行分组(GroupBy




/// <summary>要查询的对象</summary>
class Employee {
   public int ID { get;set; }
   public string FName { get; set; }
   public int Age { get; set; }
   public char Sex { get; set; }
}
如果对这个类的Age和Sex的连个字段进行分组,方法如下:
// 先造一些数据
List<Employee> empList = new List<Employee>();
empList.Add(new Employee() {
   ID = 1, FName = "John", Age = 23, Sex = 'M'
});
empList.Add(new Employee() {
   ID = 2, FName = "Mary", Age = 25, Sex = 'F'
});

empList.Add(new Employee() {
   ID = 3, FName = "Amber", Age = 23, Sex = 'M'
});
empList.Add(new Employee() {
   ID = 4, FName = "Kathy", Age = 25, Sex = 'M'
});
empList.Add(new Employee() {
   ID = 5, FName = "Lena", Age = 27, Sex = 'F'
});

empList.Add(new Employee() {
   ID = 6, FName = "Bill", Age = 28, Sex = 'M'
});

empList.Add(new Employee() {
   ID = 7, FName = "Celina", Age = 27, Sex = 'F'
});
empList.Add(new Employee() {
   ID = 8, FName = "John", Age = 28, Sex = 'M'
});
接下来的做法是:
// 实现多key分组的扩展函数版本
var sums = empList
         .GroupBy(x => new { x.Age, x.Sex })
         .Select(group => new {
            Peo = group.Key, Count = group.Count()
         });
foreach (var employee in sums) {
   Console.WriteLine(employee.Count + ": " + employee.Peo);
}

// 实现多key分组的lambda版本
var sums2 = from emp in empList
            group emp by new { emp.Age, emp.Sex } into g
            select new { Peo = g.Key, Count = g.Count() };
foreach (var employee in sums) {
   Console.WriteLine(employee.Count + ": " + employee.Peo);
}
这个例子中就充分利用了匿名类型
View Code

 

Linq的OrderBy支持动态字段

https://blog.csdn.net/leftfist/article/details/48444587

调用:

IQueryable<User> userQuery = ...;
//正序
userQuery = userQuery.OrderBy("Code");
//降序
userQuery = userQuery.OrderByDescending("Code");




 public static class QueryableExtension
    {
        public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> query, string propertyName)
        {
            return _OrderBy<T>(query, propertyName, false);
        }
        public static IOrderedQueryable<T> OrderByDescending<T>(this IQueryable<T> query, string propertyName)
        {
            return _OrderBy<T>(query, propertyName, true);
        }

        static IOrderedQueryable<T> _OrderBy<T>(IQueryable<T> query, string propertyName,bool isDesc)
        {
            string methodname = (isDesc) ? "OrderByDescendingInternal" : "OrderByInternal";

            var memberProp = typeof(T).GetProperty(propertyName);

            var method = typeof(QueryableExtension).GetMethod(methodname)
                                       .MakeGenericMethod(typeof(T), memberProp.PropertyType);

            return (IOrderedQueryable<T>)method.Invoke(null, new object[] { query, memberProp });
        }
        public static IOrderedQueryable<T> OrderByInternal<T, TProp>(IQueryable<T> query, PropertyInfo memberProperty)
        {//public
            return query.OrderBy(_GetLamba<T, TProp>(memberProperty));
        }
        public static IOrderedQueryable<T> OrderByDescendingInternal<T, TProp>(IQueryable<T> query, PropertyInfo memberProperty)
        {//public
            return query.OrderByDescending(_GetLamba<T, TProp>(memberProperty));
        }
        static Expression<Func<T, TProp>> _GetLamba<T, TProp>(PropertyInfo memberProperty)
        {
            if (memberProperty.PropertyType != typeof(TProp)) throw new Exception();

            var thisArg = Expression.Parameter(typeof(T));
            var lamba = Expression.Lambda<Func<T, TProp>>(Expression.Property(thisArg, memberProperty), thisArg);

            return lamba;
        }
    }
View Code

  

Linq语法

//linq - DicTionary 排序
  var dicResut = from pair in dicReturn
                           orderby pair.Value descending
                           select pair;

            int count = 0;
            foreach (var dic in dicResut)
            {
                if (count < 3)
                {
                    pzl3 += double.Parse(dic.Value.ToString());
                    str_max_pzl += dic.Key + "";
                }
                count++;
                pzlAll += double.Parse(dic.Value.ToString());
            }



   //distinct 去重 -使用匿名方法
            List<Person> delegateList = personList.Distinct(new Compare<Person>(
                delegate(Person x, Person y)
                {
                    if (null == x || null == y) return false;
                    return x.ID == y.ID;
                })).ToList();
 


//linq- DataTable 分组--项目添加引用 System.Data.DataSetExtensions
  var hdlx_collection = from c in dt.AsEnumerable()
                                  group c by c.Field<string>("hdlx") into g
                                  select new
                                  {
                                      hdlx = g.Key,
                                      hdzcs = g.Sum(s => s.Field<Int32>("hdzcs")),
                                      kczcs = g.Sum(s => s.Field<Int32>("kczcs"))
                                  };
            foreach (var item in hdlx_collection)
            {
                DataRow row = dt.NewRow();
                row["hdlx"] = item.hdlx + "合计:";
                row["hdzcs"] = item.hdzcs; 
                row["kczcs"] = item.kczcs;
                dt.Rows.Add(row);
            } 


//linq- DataTable 查到 list集合 
//1、项目必须是.net framework 3.5 及以上
//2、项目引用中添加了System.Data.DataSetExtensions
//3、using System.Data;
List<string> s = (from dt in ds_tbl_maintable_new.Tables[0].AsEnumerable() select dt.Field<string>("sys_orderid")).ToList<string>();

//int类型 在 DataTable 中是 decimal 类型
List<string> s2 = (from dt in ds_tbl_maintable_new.Tables[0].AsEnumerable() select (dt.Field<decimal>("sys_id")).ToString()).ToList<string>();





//datatable 去重 --项目添加引用 System.Data.DataSetExtensions
  if (ds_htxx_zb_16 != null && ds_htxx_zb_16.Tables.Count > 0 && ds_htxx_zb_16.Tables[0] != null && ds_htxx_zb_16.Tables[0].Rows.Count > 0)
                    { 
                        DataSet dsTemp=ds_htxx_zb_16.Clone();

                        var rows = from row in ds_htxx_zb_16.Tables[0].AsEnumerable() group row by row["fk_tbl_maintable_sys_id"] into myrow select myrow.FirstOrDefault();
                        foreach (DataRow row in rows)
                        {
                            dsTemp.Tables[0].Rows.Add(row.ItemArray);
                        }
                        ds_htxx_16 = dsTemp;
                    }



listModel取某一列的所有值
    List<string> list_appcode == (from model_temp in _list_model_tbl_8_update select model_temp.f_appnameid).ToList<string>();
                  



双重循环
      var list1 = from t in teachers
                        from s in t.Students
                        where s.Score < 60
                        select s;



LINQ分页
l_tbl_zzbcx_xx_Cur = l_tbl_zzbcx_xx_all.Take(pageSize * pageIndex).Skip(pageSize * (pageIndex - 1)).ToList(); 



//合并相同项
public class model {
        public string name { get; set; }
        public int gz { get; set; }
        public int qian { get; set; }
    }
List<model> list = new List<model>();
            list.Add(new model { name = "张三", gz = 1000, qian = 2000 });
            list.Add(new model { name = "李四", gz = 1100, qian = 2500 });
            list.Add(new model { name = "张三", gz = 600, qian = 1200 });

这里根据list中model对象的name字段去合并name值相同的数据,请问应该怎么去做。
想要的结果:
 { name = "李四", gz = 1100, qian = 2500 } 
  { name = "张三", gz = 1600, qian = 3200 } 

 list.groupby(m=>m.name).select(m=>new{name=m.key,gz=m.sum(a=>a.gz),qian=m.sum(a=>a.qian)})









//datatable 分組
    var data = dt.Rows.Cast<DataRow>().GroupBy(x => x["收件号"]);
 
            foreach (var d in data)
            {
                DataTable dtg = d.CopyToDataTable();

                for (int i = 0; i < dtg.Rows.Count; i++)
                {
        }
            }

//datatable 分組
var query = from t in dt.AsEnumerable()
            group t by new { t1 = t.Field<string>("name"), t2 = t.Field<string>("sex") } into m
            select new
            {
                name = m.Key.t1,
                sex = m.Key.t2,
                score = m.Sum(n => n.Field<decimal>("score"))
            };
if (query.ToList().Count > 0)
{
    query.ToList().ForEach(q =>
    {
        Console.WriteLine(q.name + "," + q.sex + "," + q.score);
    });
} 






///listmodel 排序
            l_model_all.Sort(delegate(model.tbl_cxtj_xryrkhqk m1, model.tbl_cxtj_xryrkhqk m2) { return int.Parse(m1.bm3id) - int.Parse(m2.bm3id); });
View Code

 

枚举循环.txt

public enum 
testenum { aa, bb, cc, dd };

foreach (testenum item in Enum.GetValues(typeof(testenum)))
{

}
Enum.GetValues(typeof(枚举的名称));可以获得指定枚举的枚举值。
Enum.GetNames(typeof(枚举的名称));可以获得指定枚举的枚举名称。




将字符串转换成 枚举
(route) Enum.Parse(typeof(route), control.Tag.ToString(),true)





(int)Enum.Parse(typeof(temp), "A")
View Code

 

List比较去重

代码

    class ListDistinctDemo
    {
        static void Main(string[] args)
        {
            List<Person> personList = new List<Person>(){
                new Person(3),//重复数据
                new Person(3),
                new Person(2),
                new Person(1)
            };

            //使用匿名方法
            List<Person> delegateList = personList.Distinct(new Compare<Person>(
                delegate(Person x, Person y)
                {
                    if (null == x || null == y) return false;
                    return x.ID == y.ID;
                })).ToList();

            delegateList.ForEach(s => Console.WriteLine(s.ID));

            //使用 Lambda 表达式
            List<Person> lambdaList = personList.Distinct(new Compare<Person>(
                (x, y) => (null != x && null != y) && (x.ID == y.ID))).ToList();

            lambdaList.ForEach(s => Console.WriteLine(s.ID));

            //排序
            personList.Sort((x, y) => x.ID.CompareTo(y.ID));
            personList.ForEach(s => Console.WriteLine(s.ID));

        }
    }
    public class Person
    {
        public int ID { get; set; }
        public string Name { get; set; }
        
        public Person(int id)
        {
            this.ID = id;
        }
    }

    public delegate bool EqualsComparer<T>(T x, T y);

    public class Compare<T> : IEqualityComparer<T>
    {
        private EqualsComparer<T> _equalsComparer;

        public Compare(EqualsComparer<T> equalsComparer)
        {
            this._equalsComparer = equalsComparer;
        }

        public bool Equals(T x, T y)
        {
            if (null != this._equalsComparer)
                return this._equalsComparer(x, y);
            else
                return false;
        }

        public int GetHashCode(T obj)
        {
            return obj.ToString().GetHashCode();
        }
    }
View Code

Dictionary循环

    Dictionary<int, int> d = new Dictionary<int, int>();
    d.Add(1, 1);

    for (int index = 0; index < d.Count; index++)
    {
      var item = d.ElementAt(index);
      var itemKey = item.Key;
      var itemValue = item.Value;
    }
View Code

 

DataTable扩展属性

                dt.ExtendedProperties.Add("TableSuffix", "12321");//增加属性

                //string s = dt.ExtendedProperties["TableSuffix"].ToString();//获取方法 
View Code

 

 DataTable转换成ListModel

   static class Express
    {
        /// <summary>
        /// DataSet 数据 转换 成 List<T> 类型
        /// </summary>
        /// <typeparam name="T"> model 数据模型</typeparam>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        public static List<T> TransToModel<T>(this DataTable dt) where T : class, new()
        {
            T model;

            DateTime dTime = DateTime.Parse("1900-1-1");

            List<T> listModel = new List<T>();

            Type typeModel = (new T()).GetType();

            FieldInfo[] fields = typeModel.GetFields();

            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    model = Activator.CreateInstance(typeModel) as T;

                    foreach (FieldInfo field in fields)
                    {
                        switch (field.FieldType.Name.ToString())
                        {
                            case "DateTime":
                                {
                                    dTime = DateTime.Parse("1900-1-1");

                                    DateTime.TryParse(dt.Rows[i][field.Name].ToString(), out dTime);

                                    field.SetValue(model, dTime);
                                }
                                break;
                            case "":
                                break;
                            default:
                                field.SetValue(model, dt.Rows[i][field.Name].ToString());
                                break;
                        }
                    }

                    listModel.Add(model);
                }

            }
             
            return listModel;
        }

    }
View Code

 

DataView

DataView排序

当排序列为string 时,给datatable 增加一列 (这一列是把string 转换成 int )做为排序列

   _ds.Tables[0].Columns.Add("OrderSort", System.Type.GetType("System.Int32"));
            _ds.Tables[0].Columns["OrderSort"].Expression = "Convert(f_xh,'System.Int32')";
             

            DataView dv = _ds.Tables[0].DefaultView;
            if (ViewState["GridSortOrder"].ToString() != "" && ViewState["GridSortDire"].ToString() != "")
            {
                dv.Sort = ViewState["GridSortOrder"].ToString() + " " + ViewState["GridSortDire"].ToString();
            }
       
View Code

 

反射循环Model生成ListModel

        /// <summary>
        /// 反射循环 Model生成List<Model>
        /// </summary>
        /// <param name="ds"></param> 
        private void GetModel(DataSet ds)
        {
            List<Model> listModel = new List<Model>();

            Model model = new Model(); 

            Type typeModel = model.GetType();
            FieldInfo[] fields = typeModel.GetFields();

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                model = Activator.CreateInstance(typeModel) as Model;

                foreach (FieldInfo field in fields)
                {
                    if (field.FieldType.Name.Equals("DateTime"))
                    {
                        field.SetValue(model, DateTime.Parse(ds.Tables[0].Rows[i][field.Name].ToString()));
                    }
                    else
                    {
                        field.SetValue(model, ds.Tables[0].Rows[i][field.Name].ToString());
                    }
                }
                listModel.Add(model);
            } 
        }
         

   /// <summary>
        /// DataSet 数据 转换 成 List<T> 类型
        /// </summary>
        /// <typeparam name="T"> model 数据模型</typeparam>
        /// <param name="ds">DATASET</param>
        /// <returns></returns>
        public List<T> GetListModelExcel<T>(DataSet ds) where T : class ,new()
        {
            T model;

            DateTime dTime = DateTime.Parse("1900-1-1");
            List<T> list_model = new List<T>();
            Type typeMode = (new T()).GetType();
            FieldInfo[] fields = typeMode.GetFields();

            if (ds != null && ds.Tables.Count > 0 && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    model = Activator.CreateInstance(typeMode) as T;

                    foreach (FieldInfo field in fields)
                    {
                        if (field.FieldType.Name.ToString() == "DateTime")
                        {
                            dTime = DateTime.Parse("1900-1-1");
                            DateTime.TryParse(ds.Tables[0].Rows[i][field.Name].ToString(), out dTime);
                            field.SetValue(model, dTime);
                        }
                        else
                        {
                            field.SetValue(model, ds.Tables[0].Rows[i][field.Name].ToString());
                        }
                    }
                    list_model.Add(model);
                }
            }
            return list_model;
        }





 /// <summary>
        /// 反射
        /// </summary>
        /// <param name="str_ass_name"></param>
        /// <param name="str_ass_classname"></param>
        /// <param name="str_ass_functionname"></param>
        /// <param name="obj_ass_functionparameters"></param>
        /// <returns></returns>
        public string GetResultByParameters(string str_ass_name, string str_ass_classname, string str_ass_functionname, Object[] obj_ass_functionparameters)
        {
            Assembly _ass = Assembly.Load(str_ass_name);
            Type _type = _ass.GetType(str_ass_name + "." + str_ass_classname);
            Object _obj = Activator.CreateInstance(_type);
            MethodInfo meth = _type.GetMethod(str_ass_functionname);

            return (string)(meth.Invoke(_obj, obj_ass_functionparameters));
        } 
View Code

 

随机数 

///不重复的随机数
 Random rd = new Random(Guid.NewGuid().GetHashCode());






int iSeed=10; 
Random ro = new Random(10); 
long tick = DateTime.Now.Ticks; 
Random ran = new Random((int)(tick & 0xffffffffL) | (int) (tick >> 32));

这样可以保证99%不是一样。

之后,我们就可以使用这个Random类的对象来产生随机数,这时候要用到Random.Next()方法。这个方法使用相当灵活,你甚至可以指定产生的随机数的上下限。

不指定上下限的使用如下: 
int iResult; 
iResult=ro.Next();

下面的代码指定返回小于100的随机数: 
int iResult; 
int iUp=100; 
iResult=ro.Next(iUp);

而下面这段代码则指定返回值必须在50-100的范围之内: 
int iResult; 
int iUp=100; 
int iDown=50; 
iResult=ro.Next(iDown,iUp);

除了Random.Next()方法之外,Random类还提供了Random.NextDouble()方法产生一个范围在0.0-1.0之间的随机的双精度浮点数: 
double dResult; 
dResult=ro.NextDouble();

 
View Code

 

Brush用法

// (实心刷)
                  Rectangle  myrect1 = new Rectangle(20, 80, 250, 100);
                 SolidBrush  mysbrush1 = new SolidBrush(Color.DarkOrchid);                  
                 SolidBrush  mysbrush2 = new SolidBrush(Color.Aquamarine);      
                  SolidBrush  mysbrush3 = new SolidBrush(Color.DarkOrange); 

     //(梯度刷)
                  LinearGradientBrush  mylbrush5 = new LinearGradientBrush(rect1,
                  Color.DarkOrange, Color.Aquamarine,
                  LinearGradientMode.BackwardDiagonal); 

                 //(阴影刷)
                 HatchBrush  myhbrush5 = new HatchBrush(HatchStyle.DiagonalCross,
                  Color.DarkOrange, Color.Aquamarine);
                  HatchBrush  myhbrush2 = new HatchBrush(HatchStyle.DarkVertical,
                  Color.DarkOrange, Color.Aquamarine);
                  HatchBrush  myhbrush3 = new HatchBrush(HatchStyle.LargeConfetti,
                  Color.DarkOrange, Color.Aquamarine); 

                 //(纹理刷)
                  TextureBrush textureBrush = new TextureBrush(new Bitmap(@"e:\123.jpg"));
                  e.Graphics.FillRectangle(mysbrush1, rect1);         // (实心刷)
       e.Graphics.FillRectangle(mylbrush1, rect1);            //(梯度刷)

              e.Graphics.FillRectangle(myhbrush1, rect1);             //(阴影刷)      
                 e.Graphics.FillRectangle(mytextureBrush, rect1);       //(纹理刷)

------------------------------------

using System.Windows.Media;

1、String转换成Color

            Color color = (Color)ColorConverter.ConvertFromString(string);

2、String转换成Brush

            BrushConverter brushConverter = new BrushConverter();
             Brush brush = (Brush)brushConverter.ConvertFromString(string);

3、Color转换成Brush

            Brush brush = new SolidColorBrush(color));

4、Brush转换成Color有两种方法:

(1)先将Brush转成string,再转成Color。

            Color color= (Color)ColorConverter.ConvertFromString(brush.ToString());

(2)将Brush转成SolidColorBrush,再取Color。

            Color color= ((SolidColorBrush)CadColor.Background).Color;
View Code

 

ORACLE条件数据不能超过1000解决

     private String GetOracleSQLIn(string s_ids, String field)
        {
            List<string> ids = s_ids.Split(',').ToList();
            int count = 1000;
            int len = ids.Count();
            int size = len % count;
            if (size == 0)
            {
                size = len / count;
            }
            else
            {
                size = (len / count) + 1;
            }
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < size; i++)
            {
                int fromIndex = i * count;
                int toIndex = Math.Min(fromIndex + count, len);
                string sqlids = "";
                for (int j = fromIndex; j < toIndex; j++)
                {
                    sqlids += ids[j] + ",";
                }
                if (sqlids != "")
                {
                    sqlids = sqlids.Substring(0, sqlids.Length - 1);
                }
                if (i != 0)
                {
                    builder.Append(" or ");
                }
                builder.Append(field).Append(" in ('").Append(sqlids.Replace(",", "','")).Append("')");
            }

            return "(" + builder.ToString() + ")";
        }
View Code

 

虚拟路径、物理路径转换

//转换成物理路径

string fileFullName = System.Web.HttpContext.Current.Server.MapPath(fileRootPath);                                      
View Code

 

NvalTextValue可重复键值对

  public class NvalTextValue<Ttext, Tvalue> //: IEnumerable<KeyValuePair<Ttext, Tvalue>>
    {
        #region --变量及属性--
        private List<KeyValuePair<Ttext, Tvalue>> nval;

        public int Count
        {
            get { return nval.Count; }
        }
        #endregion

        #region --构造函数--
        /// <summary>
        /// 构造函数
        /// </summary>
        public NvalTextValue()
        {
            nval = new List<KeyValuePair<Ttext, Tvalue>>();
        }
        #endregion

        #region --增加项--
        /// <summary>
        /// 为集合增加一条数据
        /// </summary>
        /// <param name="text"></param>
        /// <param name="value"></param>
        public void Add(Ttext text, Tvalue value)
        {
            nval.Add(new KeyValuePair<Ttext, Tvalue>(text, value));
        }

        public void Add(KeyValuePair<Ttext, Tvalue> pair)
        {
            nval.Add(pair);
        }

        public void AddRange(KeyValuePair<Ttext, Tvalue>[] pairs)
        {
            nval.AddRange(pairs);
        }

        #endregion

        #region --清除项--
        /// <summary>
        /// 跟据条件删除项
        /// </summary>
        /// <param name="text"></param>
        public void Remove(Ttext text)
        {
            List<KeyValuePair<Ttext, Tvalue>> nvalNew = new List<KeyValuePair<Ttext, Tvalue>>();

            foreach (KeyValuePair<Ttext, Tvalue> pair in nval)
            {
                if (!pair.Key.Equals(text))
                {
                    nvalNew.Add(pair);
                }
            }
        }

        /// <summary>
        /// 跟据条件删除项
        /// </summary>
        /// <param name="text"></param>
        /// <param name="value"></param>
        public void Remove(Ttext text, Tvalue value)
        {
            List<KeyValuePair<Ttext, Tvalue>> nvalNew = new List<KeyValuePair<Ttext, Tvalue>>();

            foreach (KeyValuePair<Ttext, Tvalue> pair in nval)
            {
                if (!pair.Key.Equals(text) || !pair.Value.Equals(value))
                {
                    nvalNew.Add(pair);
                }
            }
            nval = nvalNew;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="pairs"></param> 
        public void Remove(KeyValuePair<Ttext, Tvalue>[] pairs)
        {
            NvalTextValue<Ttext, Tvalue> nvalNew = new NvalTextValue<Ttext, Tvalue>();

            foreach (KeyValuePair<Ttext, Tvalue> pair in pairs)
            {
                if (!nval.Contains(pair))
                {
                    nvalNew.Add(pair);
                }
            }
            nval = nvalNew;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="index"></param>
        public void Remove(int index)
        {
            nval.Remove(nval[index]);
        }

        /// <summary>
        /// 清除集合中的所有数据
        /// </summary>
        public void Clear()
        {
            this.nval.Clear();
        }
        #endregion

        #region --查找项--
        /// <summary>
        /// 所引器
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public KeyValuePair<Ttext, Tvalue> this[int index]
        {
            get
            {
                if (index > nval.Count - 1)
                {
                    throw new Exception("索引超过数组界限");
                }
                else
                {
                    return nval[index];
                }
            }
        }

        /// <summary>
        /// 跟据对应的键取得 List<值>
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public List<Tvalue> GetNvalValue(Ttext text)
        {
            List<Tvalue> lValue = new List<Tvalue>();

            foreach (KeyValuePair<Ttext, Tvalue> pair in nval)
            {
                if (pair.Key.Equals(text))
                {
                    lValue.Add(pair.Value);
                }
            }

            return lValue;
        }
        #endregion

        #region --排序--

        /// <summary>
        /// 优先跟据text排序,其次跟据value排序
        /// </summary>
        public void OrderByTextValue()
        {
            nval = nval.OrderBy(d => d.Key).ThenBy(d => d.Value).ToList();
        }

        /// <summary>
        /// 优先跟据value排序,其次跟据text排序
        /// </summary>
        public void OrderByValueText()
        {
            nval = nval.OrderBy(d => d.Value).ThenBy(d => d.Key).ToList();
        }

        public IOrderedEnumerable<KeyValuePair<Ttext, Tvalue>> OrderBy(Func<KeyValuePair<Ttext, Tvalue>, Ttext> orderbyLambda)
        {
            return nval.OrderBy(orderbyLambda);
        }

        #endregion
    }

    /// <summary>
    /// 扩展类
    /// </summary>
    static public class Express
    {
        /// <summary>
        /// 扩展方法 
        /// </summary>
        /// <typeparam name="Ttext"></typeparam>
        /// <typeparam name="Tvalue"></typeparam>
        /// <param name="iEmum"></param>
        /// <returns></returns>
        public static NvalTextValue<Ttext, Tvalue> ToNvalTextValue<Ttext, Tvalue>(this IOrderedEnumerable<KeyValuePair<Ttext, Tvalue>> iEmum)
        {
            NvalTextValue<Ttext, Tvalue> nval = new NvalTextValue<Ttext, Tvalue>();

            nval.AddRange(iEmum.ToArray());

            return nval;
        }
    }
View Code

 

 HTTP访问获取返回值

   /// <summary>
        /// HTTP方式获取内容
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetHttpRepuest(string url)
        {
            string strBuff = "";
            Uri httpURL = new Uri(url);
            ///HttpWebRequest类继承于WebRequest,并没有自己的构造函数,需通过WebRequest的Creat方法 建立,并进行强制的类型转换   
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(httpURL);
            ///通过HttpWebRequest的GetResponse()方法建立HttpWebResponse,强制类型转换   
            HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
            ///GetResponseStream()方法获取HTTP响应的数据流,并尝试取得URL中所指定的网页内容   
            ///若成功取得网页的内容,则以System.IO.Stream形式返回,若失败则产生ProtoclViolationException错 误。在此正确的做法应将以下的代码放到一个try块中处理。这里简单处理   
            Stream respStream = httpResp.GetResponseStream();
            ///返回的内容是Stream形式的,所以可以利用StreamReader类获取GetResponseStream的内容,并以   
            //StreamReader类的Read方法依次读取网页源程序代码每一行的内容,直至行尾(读取的编码格式:UTF8)   
            StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
            strBuff = respStreamReader.ReadToEnd();
            return strBuff;  
        }
        
View Code

 

二、EXCEL操作

 

1. C#操作EXCEL

 private void ExportToExcel(DataSet ds)
        {
            try
            {
                SaveFileDialog saveF = new SaveFileDialog();
                saveF.Filter = " Excel files(*.xls)|*.xls";//设置文件类型
                saveF.FilterIndex = 2;//设置默认文件类型显示顺序   
                saveF.RestoreDirectory = true; //保存对话框是否记忆上次打开的目录   
                saveF.FileName = System.DateTime.Now.ToString("yyyy-MM-dd") + "单独退费名单";
                if (saveF.ShowDialog() == DialogResult.OK)
                {
                    string filePath = saveF.FileName.ToString();
                    Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
                    if (excelApp == null)
                    {
                        MessageBox.Show("无法创建Excel对象,可能您的机子未安装Excel");
                        return;
                    }
                    excelApp.DisplayAlerts = true;//保存时不提示

                    System.Diagnostics.Process[] xlPrcArray = System.Diagnostics.Process.GetProcessesByName("EXCEL");
                    System.Diagnostics.Process newExcelPrc = xlPrcArray[0];//新建一个EXCEL进程

                    //确定新建Excel文件的进程   
                    for (int i = 0; i < xlPrcArray.Length; i++)
                    {
                        if (xlPrcArray[i].TotalProcessorTime.TotalSeconds < newExcelPrc.TotalProcessorTime.TotalSeconds)
                        {
                            newExcelPrc = xlPrcArray[i];
                        }
                    }

                    Microsoft.Office.Interop.Excel.Workbook workBook = excelApp.Workbooks.Add(Type.Missing);//新建一个workbook

                    int sheetIdIndex = 0;
                    foreach (DataTable dt in ds.Tables)
                    {
                        object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];
                        for (int c = 0; c < dt.Columns.Count; c++)
                        {
                            rawData[0, c] = dt.Columns[c].ColumnName.ToString();
                        }

                        for (int r = 0; r < dt.Rows.Count; r++)
                        {
                            for (int c = 0; c < dt.Columns.Count; c++)
                            {
                                rawData[r + 1, c] = dt.Rows[r][c].ToString();
                                if (dt.Rows[r][c].GetType().ToString().ToUpper() == "DATE")
                                {
                                    rawData[r + 1, c] = DateTime.Parse(dt.Rows[r][c].ToString()).ToString("yyyy-MM-dd hh24:mi:ss");
                                }
                            }
                        }

                        Microsoft.Office.Interop.Excel.Worksheet workSheet = new Microsoft.Office.Interop.Excel.Worksheet();//新建一个workbook
                        workSheet = workBook.Sheets.Add(
                            workBook.Sheets.get_Item(++sheetIdIndex),
                            Type.Missing,
                            1,
                            Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet
                            );

                        if (dt.TableName == "")
                        {
                            workSheet.Name = "ExcelSheet" + sheetIdIndex;
                        }
                        else
                        {
                            workSheet.Name = dt.TableName;
                        }

                        string finalColLetter = string.Empty;
                        string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                        int colCharsetLen = colCharset.Length;
                        if (dt.Columns.Count > colCharsetLen)
                        {
                            finalColLetter = colCharset.Substring((dt.Columns.Count - 1) / colCharsetLen - 1, 1);
                        }
                        finalColLetter += colCharset.Substring((dt.Columns.Count - 1) % colCharsetLen, 1);
                        string excelRange = string.Format("A1:{0}{1}", finalColLetter, dt.Rows.Count + 1);

                        //workSheet.get_Range(excelRange, Type.Missing).NumberFormatLocal = "@";//文本格式 
                        //workSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;
                        //workSheet.get_Range(excelRange, Type.Missing).Cells.EntireColumn.AutoFit();  
                        //((Microsoft.Office.Interop.Excel.Range)workSheet.Rows[1, Type.Missing]).Font.Bold = true;//字体加粗 

                        Microsoft.Office.Interop.Excel.Range rangeAll = workSheet.get_Range(excelRange, Type.Missing);
                        rangeAll.NumberFormatLocal = "@";//文本格式 
                        rangeAll.Value2 = rawData;//给单元格赋值
                        rangeAll.Cells.EntireColumn.AutoFit();//自适应列宽
                        rangeAll.Borders.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;//指定边框
                        //range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeRight].LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous;//指定右边框
                    
                        string oneRange = string.Format("A1:{0}{1}", finalColLetter, 1);
                        Microsoft.Office.Interop.Excel.Range rangeOne = workSheet.get_Range(oneRange, Type.Missing);
                        rangeOne.RowHeight = 21;//行高
                        rangeOne.Font.Bold = true;//字体加粗 
                        rangeOne.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;//居中                             
                        
                    
                    }
                    workBook.SaveAs(filePath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing,
                         Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
                         Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                    workBook.Close(true, Type.Missing, Type.Missing);
                    workBook = null;

                    excelApp.Quit();
                    excelApp = null;
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    newExcelPrc.Kill();
                    System.Diagnostics.Process.Start(filePath); //打开刚才导出的文件   
                    // MessageBox.Show("已经将文件成功导入到路径:" + filePath); 
                }
                else
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Source + ex.Message + "\r\n文件可能正被打开!");
            }
        }
View Code

 

2. C#读取EXCEL到DataSet

 /// <summary>
        /// 读取EXCEL到 DataSet 
        /// 需要添加引用:
        /// COM -类库:Microsoft Excel 14.0 Object Library
        /// COM -类库:Microsoft Office 12.0 Object Library
        /// 项目属性-应用程序:.NET Framework 4.5
        ///         -生成:选中首选32位  
 
        /// </summary>
        /// <param name="ExcelPath">EXCEL带后坠名的全路径</param>
        /// <returns>读取结果</returns>
        public DataSet GetExcel(string ExcelPath)
        {
            //Excel的连接
            string ExcelStr = "";
            if (Path.GetExtension(ExcelPath) == ".xlsx")
            {
                ExcelStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelPath + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1;\"";
            }
            else
            {
                ExcelStr = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =" + ExcelPath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1;\"";
            }
            OleDbConnection ExcelCon = new OleDbConnection(ExcelStr);
            ExcelCon.Open();
            string strCom = " SELECT * FROM [Sheet1$]";
            OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, ExcelCon);
            DataSet myDataSet = new DataSet();
            myCommand.Fill(myDataSet);
            ExcelCon.Close();
            return myDataSet;
        }












 64位下无法使用Microsoft.Jet.OLEDB.4.0的解决方法
2013-07-08 15:35 18376人阅读 评论(1) 收藏 举报
 分类:  MSSQL(3)  
OLE DB 访问接口 'Microsoft.Jet.OLEDB.4.0' 配置为在单线程单元模式下运行,所以该访问接口无法用于分布式查询

解决办法
1.下载

ACE2010的驱动,64位的。

http://www.microsoft.com/downloads/zh-cn/details.aspx?familyid=c06b8369-60dd-4b64-a44b-84b371ede16d




E:\C#材料\程序\AccessDatabaseEngine.exe
E:\C#材料\程序\AccessDatabaseEngine64.exe
View Code

 

3. NPOI插入图片到EXCEL中

        /// <summary>
        /// 图片在单元格等比缩放居中显示
        /// </summary>
        /// <param name="cell">单元格</param>
        /// <param name="value">图片二进制流</param>
        private void SetRangeImage(ICell cell, byte[] value, int rowSpanCon, int colSpanCon)
        {
            if (value.Length == 0) return;//空图片处理
            double scalx = 0;//x轴缩放比例
            double scaly = 0;//y轴缩放比例
            int Dx1 = 0;//图片左边相对excel格的位置(x偏移) 范围值为:0~1023,超过1023就到右侧相邻的单元格里了
            int Dy1 = 0;//图片上方相对excel格的位置(y偏移) 范围值为:0~256,超过256就到下方的单元格里了
            bool bOriginalSize = false;//是否显示图片原始大小 true表示图片显示原始大小  false表示显示图片缩放后的大小
                                       ///计算单元格的长度和宽度
            double CellWidth = 0;
            double CellHeight = 0;
            int RowSpanCount = rowSpanCon;// cell.GetSpan().RowSpan;//合并的单元格行数
            int ColSpanCount = colSpanCon;// cell.GetSpan().ColSpan;//合并的单元格列数 
            int j = 0;
            for (j = 0; j < RowSpanCount; j++)//根据合并的行数计算出高度
            {
                CellHeight += cell.Sheet.GetRow(cell.RowIndex + j).Height;
            }
            for (j = 0; j < ColSpanCount; j++)
            {
                CellWidth += cell.Row.Sheet.GetColumnWidth(cell.ColumnIndex + j);
            }
            //单元格长度和宽度与图片的长宽单位互换是根据实例得出
            CellWidth = (CellWidth) / 35;
            CellHeight = (CellHeight) / 15;
            ///计算图片的长度和宽度
            MemoryStream ms = new MemoryStream(value);
            System.Drawing.Image Img = Bitmap.FromStream(ms, true);
            double ImageOriginalWidth = Img.Width;//原始图片的长度
            double ImageOriginalHeight = Img.Height;//原始图片的宽度
            double ImageScalWidth = 0;//缩放后显示在单元格上的图片长度
            double ImageScalHeight = 0;//缩放后显示在单元格上的图片宽度
            if (CellWidth > ImageOriginalWidth && CellHeight > ImageOriginalHeight)//单元格的长度和宽度比图片的大,说明单元格能放下整张图片,不缩放
            {
                ImageScalWidth = ImageOriginalWidth;
                ImageScalHeight = ImageOriginalHeight;
                bOriginalSize = true;
            }
            else//需要缩放,根据单元格和图片的长宽计算缩放比例
            {
                bOriginalSize = false;
                if (ImageOriginalWidth > CellWidth && ImageOriginalHeight > CellHeight)//图片的长和宽都比单元格的大的情况
                {
                    //double WidthSub = ImageOriginalWidth - CellWidth;//图片长与单元格长的差距
                    //double HeightSub = ImageOriginalHeight - CellHeight;//图片宽与单元格宽的差距

                    double WidthSub = ImageOriginalWidth / CellWidth;//图片长与单元格长的差距
                    double HeightSub = ImageOriginalHeight / CellHeight;//图片宽与单元格宽的差距

                    if (WidthSub > HeightSub)//长的差距比宽的差距大时,长度x轴的缩放比为1,表示长度就用单元格的长度大小,宽度y轴的缩放比例需要根据x轴的比例来计算
                    {
                        scalx = 0.98;
                        scaly = (CellWidth / ImageOriginalWidth) * ImageOriginalHeight * 0.98 / CellHeight;//计算y轴的缩放比例,CellWidth / ImageWidth计算出图片整体的缩放比例,然后 * ImageHeight计算出单元格应该显示的图片高度,然后/ CellHeight就是高度的缩放比例
                    }
                    else
                    {
                        scalx = (CellHeight / ImageOriginalHeight) * ImageOriginalWidth * 0.98 / CellWidth;
                        scaly = 0.98;
                    }
                }
                else if (ImageOriginalWidth > CellWidth && ImageOriginalHeight < CellHeight)//图片长度大于单元格长度但图片高度小于单元格高度,此时长度不需要缩放,直接取单元格的,因此scalx=1,但图片高度需要等比缩放
                {
                    scalx = 0.98;
                    scaly = (CellWidth / ImageOriginalWidth) * ImageOriginalHeight * 0.98 / CellHeight;
                }
                else if (ImageOriginalWidth < CellWidth && ImageOriginalHeight > CellHeight)//图片长度小于单元格长度但图片高度大于单元格高度,此时单元格高度直接取单元格的,scaly = 1,长度需要等比缩放
                {
                    scalx = (CellHeight / ImageOriginalHeight) * ImageOriginalWidth * 0.98 / CellWidth;
                    scaly = 0.98;
                }
                ImageScalWidth = scalx * CellWidth;
                ImageScalHeight = scaly * CellHeight;
            }
            Dx1 = Convert.ToInt32((CellWidth - ImageScalWidth) / CellWidth * 1023 / 2);
            Dy1 = Convert.ToInt32((CellHeight - ImageScalHeight) / CellHeight * 256 / 2);
            int pictureIdx = cell.Sheet.Workbook.AddPicture((Byte[])value, PictureType.PNG);
            IClientAnchor anchor = cell.Sheet.Workbook.GetCreationHelper().CreateClientAnchor();
            anchor.AnchorType = AnchorType.MoveDontResize;
            anchor.Col1 = cell.ColumnIndex;
            anchor.Col2 = cell.ColumnIndex + colSpanCon;// cell.GetSpan().ColSpan;
            anchor.Row1 = cell.RowIndex;
            anchor.Row2 = cell.RowIndex + rowSpanCon;// cell.GetSpan().RowSpan;
            anchor.Dy1 = Dy1;//图片下移量
            anchor.Dx1 = Dx1;//图片右移量,通过图片下移和右移,使得图片能居中显示,因为图片不同文字,图片是浮在单元格上的,文字是钳在单元格里的
            IDrawing patriarch = cell.Sheet.CreateDrawingPatriarch();
            IPicture pic = patriarch.CreatePicture(anchor, pictureIdx);
            if (bOriginalSize)
            {
                pic.Resize();//显示图片原始大小 
            }
            else
            {
                pic.Resize(scalx, scaly);//等比缩放   
            }
        }
View Code

 

 

三、HTML操作

 1. C#-操作HTML格式的字符串

用这个库:
http://www.codeplex.com/htmlagilitypack
 
文件已经下载到E:\C#材料\C#控件\C#对HTML读取

HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(@"<html><body><p><table id=""foo""><tr><th>hello</th></tr><tr><td>world</td></tr></table></body></html>");
 
foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table")) {
    Console.WriteLine("Found: " + table.Id);
    foreach (HtmlNode row in table.SelectNodes("tr")) {
        Console.WriteLine("row");
        foreach (HtmlNode cell in row.SelectNodes("th|td")) {
            Console.WriteLine("cell: " + cell.InnerText);
        }
    }
} 
View Code

 

2. C#-操作HTML格式的字符串

     /// <summary>
        /// 批次外键
        /// </summary>
        /// <param name="fk_tbl_maintable_sys_id"></param>
        /// <returns></returns>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetErrorMessage(string fk_tbl_maintable_sys_id)
        {
            Dictionary<string, string> resultDic = new Dictionary<string, string>();
            resultDic["result"] = "";
            resultDic["message"] = "";


            try
            {
                List<string> l_errormessageSysId = new List<string>();

                _cc = new commonclass.commonclass();

                string xmSysIds = _cc.GetXmSysIds(fk_tbl_maintable_sys_id, null);



                string[] showKeywords = { "shp图形所在行政分区", "工作图层", "底图数据", "地类底图缺失", "规划底图缺失", "规划底图规划不符", "权属底图缺失" };

                List<string> l_message = new List<string>();

                //面积计算情况
                Dictionary<string, decimal> dic_message_mjjs = new Dictionary<string, decimal>();
                dic_message_mjjs.Add("供地工作层占压情况", 0);
                dic_message_mjjs.Add("征转工作层占压情况", 0);
                dic_message_mjjs.Add("地类变更工作层占压情况", 0);
                dic_message_mjjs.Add("农田工作层占压情况", 0);
                dic_message_mjjs.Add("挂钩验收工作层占压情况", 0);
                dic_message_mjjs.Add("挂钩整体工作层占压情况", 0);

                //底图数据
                dic_message_mjjs.Add("集体使用权图层占压情况", 0);
                dic_message_mjjs.Add("储备地图层占压情况", 0);
                dic_message_mjjs.Add("基本农田图层占压情况", 0);
                //gh2\[shpid]_3_2_2_sumarea_jbnt

                //地类底图
                dic_message_mjjs.Add("地类底图缺失", 0);

                //权属底图
                dic_message_mjjs.Add("权属底图缺失", 0);


                //规划底图
                dic_message_mjjs.Add("规划底图缺失", 0);
                dic_message_mjjs.Add("规划底图规划不符-界内校验结果", 0);
                //gh2\[shpid]_1_8_1_3_shp_union_gh_jn_xml
                dic_message_mjjs.Add("规划底图规划不符-界外校验结果", 0);
                //gh2\[shpid]_1_8_2_3_shp_union_gh_jw_xml
                dic_message_mjjs.Add("规划底图规划不符-界外只征校验结果", 0);
                //gh2\[shpid]_1_8_3_3_shp_union_gh_jwzz_xml




                List<sara.cc.sp.model.tbl_maintable> l_model_tbl_maintable = _idal_tbl_maintable.GetList("sys_id in ('" + xmSysIds.Replace(",", "','") + "') ", "", "*", "", "", null);

                foreach (string xmSysId in xmSysIds.Split(','))
                {
                    sara.cc.sp.model.tbl_maintable model_tbl_maintable = l_model_tbl_maintable.Single(model_maintable => { return model_maintable.sys_id.ToString() == xmSysId; });
                    //是二次规划通过的
                    bool isAgreeRegexSecond = model_tbl_maintable.value8 == "1" ? true : false;


                    List<sara.cc.sp.model.t_upshp> l_model_t_upshp = _idal_t_upshp.GetList(" f_value10='" + xmSysId + "' and f_appcode = '25'", "", "f_resultcontent", "", "");

                    if (l_model_t_upshp.Count > 0)
                    {
                        _model_t_upshp = l_model_t_upshp[0];

                        //      《table
                        //          《tr
                        //              《td》《/td》
                        //              《td》《/td》 
                        //          《/tr》
                        //      《/table》

                        string htmlTable = Eva.Library.Format.FormatTextTool.TextReturn(_model_t_upshp.f_resultcontent).Replace("</div>", "</tr>");

                        if (htmlTable != "")
                        {
                            HtmlDocument docTable = new HtmlDocument();

                            docTable.LoadHtml(htmlTable);

                            HtmlNode table = docTable.DocumentNode.FirstChild;// ("//table")

                            foreach (HtmlNode row in table.ChildNodes)//("tr")
                            {
                                HtmlNode cell = row.ChildNodes[1];//内容列

                                HtmlAttribute cellAtt = cell.Attributes["class"];//如果单元格有错误的样式

                                if (cellAtt != null && (cellAtt.Value == "td_result_content_false" || cellAtt.Value == "td_result_content_warning"))//红色格 或黄色格
                                {
                                    if (!l_errormessageSysId.Contains(xmSysId))//记录下当前有问题的项目SYSID
                                    {
                                        l_errormessageSysId.Add(xmSysId);
                                    }

                                    foreach (string keyword in showKeywords)
                                    {
                                        if (row.ChildNodes[0].InnerText.Contains(keyword))//判断是否为需要展示的行
                                        {
                                            if (keyword == "shp图形所在行政分区")
                                            {
                                                l_message.Add(row.ChildNodes[0].InnerText + "图形跨区");
                                            }
                                            else
                                            {
                                                #region 面积计算情况

                                                HtmlNodeCollection zyqk_td = cell.SelectNodes("table/tr/td");//错误情况
                                                HtmlNode zyqk = zyqk_td.Count >= 3 ? zyqk_td[2] : null;//错误情况

                                                if (zyqk != null && zyqk.InnerText != "")
                                                {
                                                    for (int k = 0; k < dic_message_mjjs.Keys.Count; k++)
                                                    {
                                                        string key = dic_message_mjjs.Keys.ElementAt(k);
                                                        string zymjPfm = Regex.Match(zyqk.InnerText, "[0-9]*[.]?[0-9]*平方米").Value;

                                                        if (row.ChildNodes[0].InnerText.Contains(key) && zymjPfm != "")
                                                        {
                                                            decimal temp = 0;

                                                            decimal.TryParse(zymjPfm.Substring(0, zymjPfm.Length - 3), out temp);
                                                            dic_message_mjjs[key] += temp;

                                                        }

                                                        #region 二次验证
                                                        {
                                                            if (key == "基本农田图层占压情况" || key == "规划底图规划不符-界内校验结果" || key == "规划底图规划不符-界外校验结果" || key == "规划底图规划不符-界外只征校验结果")
                                                            {
                                                                decimal temp = 0;
                                                                if (isAgreeRegexSecond == true && (key.StartsWith("规划底图") || key.StartsWith("基本农田图层")))
                                                                {
                                                                    //二次规划验证通过了,不在显示这两个类型的 面积
                                                                    dic_message_mjjs[key] = temp;
                                                                }
                                                                else
                                                                {

                                                                    //获取部分2次规划后面积
                                                                    string path = Eva.Library.Configuration.ConfigurationManager.AppSettings["creatxm_datexmlpath"].ToString() + model_tbl_maintable.shpid.Substring(0, 4) + "/" + model_tbl_maintable.shpid.Substring(4, 2) + "/" + model_tbl_maintable.shpid.Substring(6, 2) + "/" + model_tbl_maintable.shpid + "/gh2/";

                                                                    try
                                                                    {

                                                                        //排除读取地类代码
                                                                        List<string> pcdlids = new List<string>();
                                                                        if (model_tbl_maintable.value3 == "单独选址")
                                                                        {
                                                                            pcdlids = "105000,105010,105020,106000,106010,106020,108000,108010,108020,112010,112020,113010,113020,109000,199000,111000".Split(',').ToList();
                                                                        }
                                                                        else
                                                                        {
                                                                            pcdlids = "105000,105010,105020,106000,106010,106020,108000,108010,108020".Split(',').ToList();
                                                                        }


                                                                        DataSet ds_temp = new DataSet();
                                                                        switch (key)
                                                                        {
                                                                            case "基本农田图层占压情况":
                                                                                ds_temp.ReadXml(path + model_tbl_maintable.shpid + "_1_7_0_2_shp_clip_gh_xml.xml");
                                                                                temp = 0;
                                                                                for (int i = 0; i < ds_temp.Tables[0].Rows.Count; i++)
                                                                                {
                                                                                    if (ds_temp.Tables[0].Rows[i]["GHDL"].ToString() == "基本农田")
                                                                                    {
                                                                                        decimal tt = 0;
                                                                                        decimal.TryParse(ds_temp.Tables[0].Rows[i]["tbmj"].ToString(), out tt);
                                                                                        temp += tt;
                                                                                    }
                                                                                }
                                                                                break;
                                                                            case "规划底图规划不符-界内校验结果":
                                                                                if (model_tbl_maintable.value8 == "0")
                                                                                {
                                                                                    ds_temp.ReadXml(path + model_tbl_maintable.shpid + "_1_8_1_3_shp_union_gh_jn_xml.xml");
                                                                                    temp = 0;
                                                                                    for (int i = 0; i < ds_temp.Tables[0].Rows.Count; i++)
                                                                                    {
                                                                                        if (!pcdlids.Contains(ds_temp.Tables[0].Rows[i]["GHDM"].ToString()))
                                                                                        {
                                                                                            decimal tt = 0;
                                                                                            decimal.TryParse(ds_temp.Tables[0].Rows[i]["tbmj"].ToString(), out tt);
                                                                                            temp += tt;
                                                                                        }
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    temp = 0;
                                                                                }
                                                                                break;
                                                                            case "规划底图规划不符-界外校验结果":
                                                                                if (model_tbl_maintable.value8 == "0")
                                                                                {
                                                                                    ds_temp.ReadXml(path + model_tbl_maintable.shpid + "_1_8_2_3_shp_union_gh_jw_xml.xml");
                                                                                    temp = 0;
                                                                                    for (int i = 0; i < ds_temp.Tables[0].Rows.Count; i++)
                                                                                    {
                                                                                        if (!pcdlids.Contains(ds_temp.Tables[0].Rows[i]["GHDM"].ToString()))
                                                                                        {
                                                                                            decimal tt = 0;
                                                                                            decimal.TryParse(ds_temp.Tables[0].Rows[i]["tbmj"].ToString(), out tt);
                                                                                            temp += tt;
                                                                                        }
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    temp = 0;
                                                                                }
                                                                                break;
                                                                            case "规划底图规划不符-界外只征校验结果":
                                                                                if (model_tbl_maintable.value8 == "0")
                                                                                {
                                                                                    ds_temp.ReadXml(path + model_tbl_maintable.shpid + "_1_8_3_3_shp_union_gh_jwzz_xml.xml"); temp = 0;
                                                                                    for (int i = 0; i < ds_temp.Tables[0].Rows.Count; i++)
                                                                                    {
                                                                                        if (!pcdlids.Contains(ds_temp.Tables[0].Rows[i]["GHDM"].ToString()))
                                                                                        {
                                                                                            decimal tt = 0;
                                                                                            decimal.TryParse(ds_temp.Tables[0].Rows[i]["tbmj"].ToString(), out tt);
                                                                                            temp += tt;
                                                                                        }
                                                                                    }
                                                                                }
                                                                                else
                                                                                {
                                                                                    temp = 0;
                                                                                }
                                                                                break;
                                                                            default:
                                                                                throw new Exception();
                                                                                break;
                                                                        }




                                                                        if (key.StartsWith("规划底图"))
                                                                        {
                                                                            if (temp >= 16)
                                                                                //规划相关需大于等于16平米 才显示
                                                                                dic_message_mjjs[key] = temp;
                                                                        }

                                                                        else
                                                                        {
                                                                            dic_message_mjjs[key] = temp;
                                                                        }

                                                                        //dic_message_mjjs.Add("基本农田图层占压情况", 0);
                                                                        ////gh2\[shpid]_3_2_3_clip_jbnt_xml

                                                                        //dic_message_mjjs.Add("规划底图规划不符-界内校验结果", 0);
                                                                        ////gh2\[shpid]_1_8_1_3_shp_union_gh_jn_xml
                                                                        //dic_message_mjjs.Add("规划底图规划不符-界外校验结果", 0);
                                                                        ////gh2\[shpid]_1_8_2_3_shp_union_gh_jw_xml
                                                                        //dic_message_mjjs.Add("规划底图规划不符-界外只征校验结果", 0);
                                                                        ////gh2\[shpid]_1_8_3_3_shp_union_gh_jwzz_xml
                                                                    }
                                                                    catch (Exception ex)
                                                                    {
                                                                        //dic_message_mjjs[key] += temp;

                                                                    }


                                                                }
                                                            }
                                                        }
                                                        #endregion

                                                    }

                                                }
                                                #endregion
                                            }

                                            break;
                                        }
                                    }

                                }

                            }
                        }

                    }



                }




                List<string> l_keywords = new List<string>();
                l_keywords.Add("占压");
                l_keywords.Add("缺失");
                l_keywords.Add("不符");

                foreach (string key in dic_message_mjjs.Keys)
                {
                    if (dic_message_mjjs[key] != 0)
                    {
                        double mj = Eva.Library.Text.NumberTool.Round(double.Parse(dic_message_mjjs[key].ToString()), 1);

                        if (mj == 0)
                        {
                            continue;
                        }

                        foreach (string keyword in l_keywords)
                        {
                            if (key.Contains(keyword))
                            {
                                l_message.Add(key + "" + keyword + "面积:" + mj.ToString() + "平方米" + "" + (decimal.Parse(mj.ToString()) / 10000).ToString() + "公顷)");

                                break;
                            }
                        }

                    }
                }



                Dictionary<string, string> dicRes = new Dictionary<string, string>();
                dicRes.Add("errorSysId", string.Join("^", l_errormessageSysId));
                dicRes.Add("errormessage", string.Join("<br/>", l_message));


                resultDic["result"] = "true";
                resultDic["message"] = Eva.Library.Format.FormatEntityTool.FormatDicToJson(dicRes);

            }
            catch (Exception ex)
            {
                resultDic["result"] = "false";
                resultDic["message"] = Eva.Library.Format.FormatTextTool.ErrorMessageFormat(ex.Message + ex.StackTrace);
            }
            return Eva.Library.Format.FormatEntityTool.FormatDicToJson(resultDic);
        }
View Code

 

 

四、数据操作

C#-Math用法

Math.abs() 计算绝对值。  
Math.acos() 计算反余弦值。  
Math.asin() 计算反正弦值。  
Math.atan() 计算反正切值。  
Math.atan2() 计算从x 坐标轴到点的角度。  
Math.ceil() 将数字向上舍入为最接近的整数。  
Math.cos() 计算余弦值。  
Math.exp() 计算指数值。  
Math.floor() 将数字向下舍入为最接近的整数。  
Math.log() 计算自然对数。  
Math.max() 返回两个整数中较大的一个。  
Math.min() 返回两个整数中较小的一个。  
Math.pow() 计算x 的y 次方。  
Math.random() 返回一个0.0 与1.0 之间的伪随机数。  
Math.round() 四舍五入为最接近的整数。  
Math.sin() 计算正弦值。  
Math.sqrt() 计算平方根。  
Math.tan() 计算正切值。  
Math.E 欧拉(Euler) 常数,自然对数的底(大约为2.718)。  
Math.LN2 2 的自然对数(大约为0.693)。  
Math.LOG2E e 的以2 为底的对数(大约为1.442)。  
Math.LN2 10 的自然对数(大约为2.302)。  
Math.LOG10E e 的以10 为底的对数(大约为0.434)。  
Math.PI 一个圆的周长与其直径的比值(大约为3.14159)。  
Math.SQRT1_2 1/2 的平方根的倒数(大约为0.707)。  
Math.SQRT2 2 的平方根(大约为1.414)。
View Code

C#-Float类型取整

若A=23.56,要想得到 B=23,C=0.56 
floor 直接往小的取,比如 floor(-23.56)=-24,floor(23.56)=23
trunc 直接切下整数,比如 trunc(-23.56)=-23搜索, floor(23.56)=23
ceil  直接往大的取,比如 ceil(-23.56)=-23, ceil(23.56)=24
round 计算四舍五入,比如 round(-23.56)=-24,round(23.56)=24 
取整部分利用取整函数就可以;
取小数部分就是用原来的数减去取整部分,剩下的就是小数部分了。
View Code

C#-数组去除项

                            ArrayList al = new ArrayList(values);

                            al.Remove("tbl_110_pc_scyj");

                            values = (string[])al.ToArray(typeof(string));
View Code

 

五、文件操作

C#-文件打开

                            ArrayList al = new ArrayList(values);

                            al.Remove("tbl_110_pc_scyj");

                            values = (string[])al.ToArray(typeof(string));
View Code

 

C#-文件夹打开

            //OpenFileDialog o = new OpenFileDialog();

            //o.Filter = "xml文件|*.config";

            //o.Multiselect = true;

            //if (o.ShowDialog() == DialogResult.OK)
            //{

            //    string[] filePaths = o.FileNames;

            //    OpenFiles(filePaths);
            //}


            string csPath = @"E:\Project Visio Studio\Cproject3\OtherTools\OtherTools\Text";

            DirectoryInfo dirInfo = new DirectoryInfo(csPath);

            foreach (FileInfo fInfo in dirInfo.GetFiles("*.config"))
            {
                string[] sPath = { fInfo.FullName };

                OpenFiles(sPath);
            }
View Code

 

C#-文件删除

             //永久删除
                    //FileInfo fInfo = new FileInfo(filePath);
                    //fInfo.Delete();

                    //永久删除 
                    //File.Delete(filePath);

                    //删除到回收站 
            //添加引用Microsoft.VisualBasic,using Microsoft.VisualBasic.FileIO;
                    FileSystem.DeleteFile(filePath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);


                
                    Console.WriteLine("删除文件到回收站");
                    stringfilepath = "leaver.txt";
                    FileSystem.DeleteFile(filepath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
                    Console.WriteLine("删除文件完成");

                    Console.WriteLine("删除文件夹到回收站");
                    stringdirpath = "leaver";
                    FileSystem.DeleteDirectory(dirpath, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
                    Console.WriteLine("删除文件夹完成");
View Code

C#-文件下载

  System.Net.WebClient myWebClient = new System.Net.WebClient();
                myWebClient.DownloadFile(fjPathSource, fjPathTask);
View Code

C#-文件写日志

        private string WriteLog(string text)
        {
            string message = "";
            System.IO.FileStream sfile = new System.IO.FileStream(AppDomain.CurrentDomain.BaseDirectory + "/TransData_LOLANALANDDC_DataCenter_Log.txt", FileMode.Append, FileAccess.Write);
            StreamWriter myfile = new StreamWriter(sfile);
            try
            {
                myfile.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "@" + text);
                myfile.Flush();
                myfile.Close();
                sfile.Close();
            }
            catch (Exception ex)
            {
                if (myfile != null)
                {
                    myfile.Flush();
                    myfile.Close();
                }
                if (sfile != null)
                {
                    sfile.Close();
                }
                message += ex.Source + ex.Message;
            }
            return message;
        }
        private string WriteLog(List<string> l_text)
        {
            string message = "";
            System.IO.FileStream sfile = new System.IO.FileStream(AppDomain.CurrentDomain.BaseDirectory + "/TransData_LOLANALANDDC_DataCenter_Log.txt", FileMode.Append, FileAccess.Write);
            StreamWriter myfile = new StreamWriter(sfile);
            try
            {
                for (int i = 0; i < l_text.Count; i++)
                {
                    myfile.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "@" + l_text[i]);
                }
                myfile.Flush();
                myfile.Close();
                sfile.Close();
            }
            catch (Exception ex)
            {
                if (myfile != null)
                {
                    myfile.Flush();
                    myfile.Close();
                }
                if (sfile != null)
                {
                    sfile.Close();
                }
                message += ex.Source + ex.Message;
            }
            return message;
        }
View Code

 

C#-网络文件确定是否存在

       /// <summary>
        /// 确证网络文件是否存在
        /// </summary>
        /// <param name="fileFullName"></param>
        /// <returns></returns>
        private bool JudgeFileExist01(string fileFullName)
        {
            int resMessage = 1;

            //创建根据网络地址的请求对象
            System.Net.HttpWebRequest httpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(new Uri(fileFullName));
            System.Net.ServicePointManager.Expect100Continue = false;
            try
            {
                //响应对象的成功状态
                ((System.Net.HttpWebResponse)httpWebRequest.GetResponse()).Close();

                resMessage = 1;
            }
            catch (System.Net.WebException exception)
            {
                if (exception.Status != System.Net.WebExceptionStatus.ProtocolError)
                { resMessage = 1; }
                if (exception.Message.IndexOf("500") > 0)
                { resMessage = 500; }
                if (exception.Message.IndexOf("401") > 0)
                { resMessage = 401; }
                if (exception.Message.IndexOf("404") > 0)
                { resMessage = 404; }
            }

            if (resMessage == 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
View Code

 

C#-网络文件操作-Form1

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication7
{
    public partial class Form1 : Form
    {
        static string address = "http://162.16.166.7/Easy2008.ServiceFile/Files/ServiceReport/Lolana.Land.DataCenter.ReportFile/dblink.txt";
        
        public Form1()
        {
            InitializeComponent();
        }

    //下载
        private void button1_Click(object sender, EventArgs e)
        {
            WebClient wc = new WebClient();
            string fileName = @"C:\Users\Administrator\Desktop\211.txt";
            wc.DownloadFile(address, fileName);
        }

    //远程读取
        private void button2_Click(object sender, EventArgs e)
        {
            WebClient wc = new WebClient();
            Stream s = wc.OpenRead(address);
            StreamReader sr = new StreamReader(s);
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                listBox1.Items.Add(line);
            }
            s.Close();
        }
    //远程读取
        private void button3_Click(object sender, EventArgs e)
        {
            WebRequest wrq = WebRequest.Create(address);
            WebResponse wrs = wrq.GetResponse();

            HttpWebRequest hwrq = (HttpWebRequest)wrq;
            listBox1.Items.Add("Request Timeout (ms) = " + wrq.Timeout);
            listBox1.Items.Add("Request Keep Alive = " + hwrq.KeepAlive);
            listBox1.Items.Add("Request AllowAutoRedirect = " + hwrq.AllowAutoRedirect);


            Stream strm = wrs.GetResponseStream();
            StreamReader sr = new StreamReader(strm);
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                listBox1.Items.Add(line);
            };
            strm.Close();
        }

    //异部操作
        private void button4_Click(object sender, EventArgs e)
        {
            WebRequest webRequest = WebRequest.Create(address);
            webRequest.BeginGetResponse(new AsyncCallback(OnResponse), webRequest);
        }

        protected static void OnResponse(IAsyncResult ir)
        {
            WebRequest wrq = (WebRequest)ir.AsyncState;
            WebResponse wrs = wrq.EndGetResponse(ir);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            this.listBox1.Items.Clear();
        }

    }
}
View Code

  

C#-网络文本文件选程读取

  /// <summary>
        /// 读取选程 txt
        /// </summary>
        /// <param name="txtPath">文件路径</param> 
        /// <returns></returns>
        private string ReadTxt(string txtPath)
        {
            string txt = "";
            try
            {
                HttpWebRequest oHttp_Web_Req = (HttpWebRequest)WebRequest.Create(txtPath);
                Stream oStream = oHttp_Web_Req.GetResponse().GetResponseStream();
                using (StreamReader respStreamReader = new StreamReader(oStream, Encoding.UTF8))
                {
                    string line = respStreamReader.ReadLine();
                }
            }
            catch (Exception ex)
            {
                throw new Exception(txtPath+",文件读取出错!");
            }

            return txt;

        }
View Code

C#-文件压缩

引用文件
E:\C#材料\C#控件\C#文件压缩-DotNetZipLib-DevKit-v1.9\Tools\Ionic.Zip.dll

 


     //待压缩的文件夹路径
            //string path1 = @"D:\zhai\办公室";
            //System.Text.Encoding.Default解决中文文件夹名称乱码
            using (ZipFile zf = new ZipFile(System.Text.Encoding.Default))
            {
                zf.AddDirectory(folderName);
                //压缩之后保存路径及压缩文件名
                zf.Save(compressedFileName);
            }



第二种方法 

E:\C#材料\C#控件\文件压缩
View Code

C#-StreamReader类

StreamReader类:
Read方法,到达尾端没有字符可以读到时,返回0.
Peek方法,如果没有字符可以读取,返回-1.
ReadLine方法,到达尾端时,返回null.
ReadBlock方法,到达尾端,没有字符可以再读时,返回0.
ReadToEnd方法,一次读完。

 
View Code

C#-获取网络地址图片

        //获取网络地址图片
        private byte[] GetWebImages(string imagePath)
        {
            byte[] dataRes = new byte[0];

            try
            {
                WebRequest request = WebRequest.Create(imagePath);
                WebResponse response = request.GetResponse();
                Stream s = response.GetResponseStream();
                byte[] data = new byte[1024];
                int length = 0;
                MemoryStream ms = new MemoryStream();
                while ((length = s.Read(data, 0, data.Length)) > 0)
                {
                    ms.Write(data, 0, length);
                }
                ms.Seek(0, SeekOrigin.Begin);

                dataRes = ms.ToArray();
            }
            catch (Exception ex)
            {
            }
            finally
            {
            }
            return dataRes;
        }
View Code

  

六、字符串操作

 C#-字符串首字母大写

System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(string str);
View Code

C#-获取字符串字节数

System.Text.Encoding.Default.GetByteCount(str);
View Code

C#-字符串全部索引

     public static int[] IndexOfAll(this string str, char value)
        {
            int indexAllTemp = 0;
            int indexSubTemp = 0;
            List<int> listIndexs = new List<int>();

            int length = str.Length;
            while (indexSubTemp != -1 && indexAllTemp < length - 1)
            {
                indexSubTemp = str.IndexOf(value);

                if (indexSubTemp != -1)
                {
                    indexAllTemp += indexSubTemp;

                    listIndexs.Add(indexAllTemp);

                    indexAllTemp++;//需要多截取一个字符,把当前的字符去掉

                    str = str.Remove(0, indexAllTemp);
                }
            }
            return listIndexs.ToArray();
        }
View Code

C#-查找字符串中对应字符的所有索引

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringExpress
{
    static class Express
    {
        /// <summary>
        /// 获得字符串中指定字符的所有索引值
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="value">字符</param>
        /// <returns></returns>
        public static int[] IndexOfAll(this string str, char value)
        {
            return str.IndexOfAll(value.ToString());
        }

        /// <summary>
        /// 获得字符串中指定字符的所有索引值
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="value">小字符串</param>
        /// <returns></returns>
        public static int[] IndexOfAll(this string str, string value)
        {
            int index = 0;

            string strTemp = str;

            List<int> listIndexs = new List<int>();

            index += strTemp.IndexOf(value);

            while (true)
            {

                listIndexs.Add(index);

                strTemp = str.Remove(0, index + value.Length);


                if (strTemp.IndexOf(value) == -1)
                {
                    break;
                }

                index += value.Length + strTemp.IndexOf(value);

            }

            return listIndexs.ToArray();
        }
    }
}
View Code

C#-加密解密字符串

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace EncryptString
{
    public  class EncryptString
    {

        private static string _sDecrKey = "20140415";


        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="strText"></param>
        /// <returns></returns>
        public static string doDecryptString(string strText)
        {
            return doDecryptString(strText, _sDecrKey);
        }
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="strText"></param>
        /// <returns></returns>
        public static string doEncryptString(string strText)
        {
            return doEncryptString(strText, _sDecrKey);
        }

        /// <summary>
        /// 字符串解密
        /// </summary>
        /// <param name="strText">字符串</param>
        /// <param name="sDecrKey">密钥8位数字</param>
        /// <returns></returns>
        private static string doDecryptString(string strText, string sDecrKey)
        {
            byte[] rgbKey = null;
            byte[] rgbIV = new byte[] { 0x12, 0x34, 0x56, 120, 0x90, 0xab, 0xcd, 0xef };
            byte[] buffer = new byte[strText.Length];
            try
            {
                rgbKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                buffer = Convert.FromBase64String(strText);
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, provider.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                stream2.Write(buffer, 0, buffer.Length);
                stream2.FlushFinalBlock();
                Encoding encoding = new UTF8Encoding();
                return encoding.GetString(stream.ToArray());
            }
            catch (Exception exception)
            {
                //return ("error:" + exception.Message + "\r");
                throw exception;
            }
        }
      

        /// <summary>
        /// 字符串加密
        /// </summary>
        /// <param name="strText">字符串</param>
        /// <param name="strEncrKey">密钥</param>
        /// <returns></returns>
        private static string doEncryptString(string strText, string strEncrKey)
        {
            byte[] rgbKey = null;
            byte[] rgbIV = new byte[] { 0x12, 0x34, 0x56, 120, 0x90, 0xab, 0xcd, 0xef };
            try
            {
                rgbKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, strEncrKey.Length));
                DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
                byte[] bytes = Encoding.UTF8.GetBytes(strText);
                MemoryStream stream = new MemoryStream();
                CryptoStream stream2 = new CryptoStream(stream, provider.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
                stream2.Write(bytes, 0, bytes.Length);
                stream2.FlushFinalBlock();
                return Convert.ToBase64String(stream.ToArray());
            }
            catch (Exception exception)
            {
                //return ("error:" + exception.Message + "\r");
                throw exception;
            }
        }
    }
}
View Code

C#-全半角转换

  /// 转全角的函数(SBC case)
        ///
        ///任意字符串
        ///全角字符串
        ///
        ///全角空格为12288,半角空格为32
        ///其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
        ///
        public static String ToSBC(String input)
        {
            // 半角转全角:
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 32)
                {
                    c[i] = (char)12288;
                    continue;
                }
                if (c[i] < 127)
                    c[i] = (char)(c[i] + 65248);
            }
            return new String(c);
        }

        /**/
        // /
        // / 转半角的函数(DBC case)
        // /
        // /任意字符串
        // /半角字符串
        // /
        // /全角空格为12288,半角空格为32
        // /其他字符半角(33-126)与全角(65281-65374)的对应关系是:均相差65248
        // /
        public static String ToDBC(String input)
        {
            char[] c = input.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                if (c[i] == 12288)
                {
                    c[i] = (char)32;
                    continue;
                }
                if (c[i] > 65280 && c[i] < 65375)
                    c[i] = (char)(c[i] - 65248);
            }
            return new String(c);
        }
         
View Code

C#-正则表达式

验证数字的正则表达式集 
验证数字:^[0-9]*$ 
验证n位的数字:^\d{n}$ 
验证至少n位数字:^\d{n,}$ 
验证m-n位的数字:^\d{m,n}$ 
验证零和非零开头的数字:^(0|[1-9][0-9]*)$ 
验证有两位小数的正实数:^[0-9]+(.[0-9]{2})?$ 
验证有1-3位小数的正实数:^[0-9]+(.[0-9]{1,3})?$ 
验证非零的正整数:^\+?[1-9][0-9]*$ 
验证非零的负整数:^\-[1-9][0-9]*$ 
验证非负整数(正整数 + 0) ^\d+$ 
验证非正整数(负整数 + 0) ^((-\d+)|(0+))$ 
验证长度为3的字符:^.{3}$ 
验证由26个英文字母组成的字符串:^[A-Za-z]+$ 
验证由26个大写英文字母组成的字符串:^[A-Z]+$ 
验证由26个小写英文字母组成的字符串:^[a-z]+$ 
验证由数字和26个英文字母组成的字符串:^[A-Za-z0-9]+$ 
验证由数字、26个英文字母或者下划线组成的字符串:^\w+$ 
验证用户密码:^[a-zA-Z]\w{5,17}$ 正确格式为:以字母开头,长度在6-18之间,只能包含字符、数字和下划线。 
验证是否含有 ^%&',;=?$\" 等字符:[^%&',;=?$\x22]+ 
验证汉字:^[\u4e00-\u9fa5],{0,}$ 
验证Email地址:^\w+[-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$ 
验证InternetURL:^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$ ;^[a-zA-z]+://(w+(-w+)*)(.(w+(-w+)*))*(?S*)?$ 
验证电话号码:^(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$:--正确格式为:XXXX-XXXXXXX,XXXX-XXXXXXXX,XXX-XXXXXXX,XXX-XXXXXXXX,XXXXXXX,XXXXXXXX。 
验证身份证号(15位或18位数字):^\d{15}|\d{}18$ 
验证一年的12个月:^(0?[1-9]|1[0-2])$ 正确格式为:“01”-“09”和“1”“12” 
验证一个月的31天:^((0?[1-9])|((1|2)[0-9])|30|31)$ 正确格式为:01、09和1、31。 
整数:^-?\d+$ 
非负浮点数(正浮点数 + 0):^\d+(\.\d+)?$ 
正浮点数 ^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$ 
非正浮点数(负浮点数 + 0) ^((-\d+(\.\d+)?)|(0+(\.0+)?))$ 
负浮点数 ^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$ 
浮点数 ^(-?\d+)(\.\d+)?$ 
View Code

C#-正则归纳

一、    数字
1.    只有一个或多个数字      
允许整数位以0开头                                ^[0-9]{1,}$
不允许整数位以0开头除非整数位只有一位            ^([1-9]{1}[0-9]{0,}|0)$
2.    浮点数   
1)    小数位与整数据位都有一个或多个  
允许整数位以0开头                                 ^[0-9]{1,}\.[0-9]{1,}$
不允许整数位以0开头除非整数位只有一位             ^([1-9]{1}[0-9]{0,}\.|0\.)[0-9]{1,}$
2)    小数位可以没有,可以有
允许整数位以0开头                                ^[0-9]{1,}(\.[0-9]{1,})?$
不允许整数位以0开头除非整数位只有一位            ^([1-9]{1}[0-9]{0,}|0)(\.[0-9]{1,})?$


二、    英文
1.    只有一个或多个英文字母不
区分大小写                                        ^[a-z|A-Z]{1,}$
小写                                              ^[a-z]{1,}$
大写                                              ^[A-Z]{1,}$
三、    汉字
1.    只有一个或多个汉字
                                                  ^[\u4e00-\u9fa5]{1,}$
View Code

C#-获取JS的GetTime()相同的值

C#获取JS的GetTime()相同的值代码如下:
public long GetTimeLikeJS()

{

long lLeft = 621355968000000000;

DateTime dt = DateTime.Now;

long Sticks = (dt.Ticks - lLeft) / 10000;

return Sticks;

}
完美模拟JS中的:
var d = new Date();

var ticks = d.getTime();
View Code

C#-ToString()格式化数据

 temp.ToString("#0.######")

去除数据末尾的0

比如12.90 格式化成12.9
View Code

  

 

七、JSON操作

Json序列化

JsonConvert(using Newtonsoft.Json)
View Code

 

 

JSON操作

winform 下引用JavaScriptSerializer
将C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.5
目录下的System.Web.Extensions.dll
复制到C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0
重新启动visio studio






【winform 学习】C# 转换成JSON对象

C#里面对json的处理有2种,JavaScriptSerializer和DataContractJsonSerializer。

JavaScriptSerializer读出来就是key-value pair这种Dictionary<string, object>的东西,这个比较通用。
DataContractJsonSerializer类似于其他的Serializer,比如XMLSerializer一类的,是对象序列化/反序列化用的

第一种示例代码:

                (测试发现using System.Web.Script.Serialization不能在Winform 中引用,所以JavaScriptSerializer 不用在winform中使用

                   那winform 下怎么解析JSON 可以参考:http://q.cnblogs.com/q/46365/  1.Json.NET  2. 引用官方的System.Web.Extensions.dll

                   dll文件:可以网上下载,或者参考下面地址的方面:http://wenku.it168.com/d_000825166.shtml):

            string jsonStr = @"{""fruits"":{""a"":""orange"",""b"":""banana"",""c"":""apple""},""name"":{""z"":""zhangsan"",""l"":""lisi""}}";
 
            JavaScriptSerializer serializer = new JavaScriptSerializer();
 
            Dictionary<string, object> json = serializer.DeserializeObject(jsonStr) as Dictionary<string, object>;
 
            Dictionary<string, object> obj = json["fruits"] as Dictionary<string, object>;
 
            Console.WriteLine(obj["a"]);
 
            Console.ReadLine();
第二种:DataContractJsonSerializer很不错,(不过,要申明DataContract数据数据契约,如果参数的名字不是固定的话,用第一种更好)

    [DataContract]
        public class DanTengObj
        {
            [DataMember(Order = 1, Name = "fruits")]
            public Fruits fruits { get; set; }
            [DataMember(Order = 2, Name = "name")]
            public Name name { get; set; }
 
            [DataContract]
            public class Fruits
            {
                [DataMember(Order = 1, Name = "a")]
                public string a { get; set; }
                [DataMember(Order = 2, Name = "b")]
                public string b { get; set; }
                [DataMember(Order = 3, Name = "c")]
                public string c { get; set; }
            }
 
            [DataContract]
            public class Name
            {
                [DataMember(Order = 1, Name = "z")]
                public string z { get; set; }
                [DataMember(Order = 1, Name = "l")]
                public string l { get; set; }
            }
        }
 
        static void DanTengJsonTest()
        {
            string jsonStr = @"{""fruits"":{""a"":""orange"",""b"":""banana"",""c"":""apple""},""name"":{""z"":""zhangsan"",""l"":""lisi""}}";
 
            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(DanTengObj));
 
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr)))
            {
                DanTengObj obj = js.ReadObject(ms) as DanTengObj;
                Console.WriteLine(obj.fruits.a);
            }
        }
View Code

 

八、WebService操作

1. C#对WebService调用

  private CustMainInfo GetCustMainInfo(string sellerCode, string custCode)
        {
            try
            {
                CustMainInfo custMainInfo = new CustMainInfo();

                string url =  ConfigurationManager.AppSettings["GetCustMainInfoUrl"];//http://10.5.30.122:8090/api/mksmart-mqadapter/hybris/customer
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "Post";
                request.ContentType = "application/json";
                string data = "{\"cmd\":\"getCustomerLevel\",\"params\":{\"weChat\":\""+sellerCode+"\",\"mobile\":\""+custCode+"\"}}";

                byte[] byteData1 = UTF8Encoding.UTF8.GetBytes(data.ToString());
                request.ContentLength = byteData1.Length;

                using (Stream postStream = request.GetRequestStream())
                {
                    postStream.Write(byteData1, 0, byteData1.Length);
                }

                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    var sstrReturn = reader.ReadToEnd();


                }

                return custMainInfo;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
View Code

 

 

九、XML操作

1. C# 对XML的操作

/// <summary>
        /// 批次外键
        /// </summary>
        /// <param name="fk_tbl_maintable_sys_id"></param>
        /// <returns></returns>
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string GetErrorMessage(string fk_tbl_maintable_sys_id)
        {
            Dictionary<string, string> resultDic = new Dictionary<string, string>();
            resultDic["result"] = "";
            resultDic["message"] = "";


            try
            {
                List<string> l_errormessageSysId = new List<string>();

                _cc = new commonclass.commonclass();

                string xmSysIds = _cc.GetXmSysIds(fk_tbl_maintable_sys_id, null);



                string[] showKeywords = { "shp图形所在行政分区", "工作图层", "底图数据", "地类底图缺失", "规划底图缺失", "规划底图规划不符", "权属底图缺失" };

                List<string> l_message = new List<string>();

                //面积计算情况
                Dictionary<string, decimal> dic_message_mjjs = new Dictionary<string, decimal>();
                dic_message_mjjs.Add("供地工作层占压情况", 0);
                dic_message_mjjs.Add("征转工作层占压情况", 0);
                dic_message_mjjs.Add("地类变更工作层占压情况", 0);
                dic_message_mjjs.Add("农田工作层占压情况", 0);
                dic_message_mjjs.Add("挂钩验收工作层占压情况", 0);
                dic_message_mjjs.Add("挂钩整体工作层占压情况", 0);

                //底图数据
                dic_message_mjjs.Add("集体使用权图层占压情况", 0);
                dic_message_mjjs.Add("储备地图层占压情况", 0);
                dic_message_mjjs.Add("基本农田图层占压情况", 0);

                //地类底图
                dic_message_mjjs.Add("地类底图缺失", 0);

                //权属底图
                dic_message_mjjs.Add("权属底图缺失", 0);


                //规划底图
                dic_message_mjjs.Add("规划底图缺失", 0);
                dic_message_mjjs.Add("规划底图规划不符-界内校验结果", 0);
                dic_message_mjjs.Add("规划底图规划不符-界外校验结果", 0);
                dic_message_mjjs.Add("规划底图规划不符-界外只征校验结果", 0);





                List<sara.cc.sp.model.tbl_maintable> l_model_tbl_maintable = _idal_tbl_maintable.GetList("sys_id in ('" + xmSysIds.Replace(",", "','") + "') ", "", "*", "", "", null);

                foreach (string xmSysId in xmSysIds.Split(','))
                {
                    //是二次规划通过的
                    bool isAgreeRegexSecond = l_model_tbl_maintable.Single(model_maintable => { return model_maintable.sys_id.ToString() == xmSysId; }).value8 == "1" ? true : false;


                    List<sara.cc.sp.model.t_upshp> l_model_t_upshp = _idal_t_upshp.GetList(" f_value10='" + xmSysId + "' and f_appcode = '25'", "", "f_resultcontent", "", "");

                    if (l_model_t_upshp.Count > 0)
                    {
                        _model_t_upshp = l_model_t_upshp[0];

                        //      《table
                        //          《tr
                        //              《td》《/td》
                        //              《td》《/td》 
                        //          《/tr》
                        //      《/table》

                        string htmlTable = Eva.Library.Format.FormatTextTool.TextReturn(_model_t_upshp.f_resultcontent).Replace("</div>", "</tr>");

                        if (htmlTable != "")
                        {
                            HtmlDocument docTable = new HtmlDocument();

                            docTable.LoadHtml(htmlTable);

                            HtmlNode table = docTable.DocumentNode.FirstChild;// ("//table")

                            foreach (HtmlNode row in table.ChildNodes)//("tr")
                            {
                                HtmlNode cell = row.ChildNodes[1];//内容列

                                HtmlAttribute cellAtt = cell.Attributes["class"];//如果单元格有错误的样式

                                if (cellAtt != null && (cellAtt.Value == "td_result_content_false" || cellAtt.Value == "td_result_content_warning"))//红色格 或黄色格
                                {
                                    if (!l_errormessageSysId.Contains(xmSysId))//记录下当前有问题的项目SYSID
                                    {
                                        l_errormessageSysId.Add(xmSysId);
                                    }

                                    foreach (string keyword in showKeywords)
                                    {
                                        if (row.ChildNodes[0].InnerText.Contains(keyword))//判断是否为需要展示的行
                                        {
                                            if (keyword == "shp图形所在行政分区")
                                            {
                                                l_message.Add(row.ChildNodes[0].InnerText + "图形跨区");
                                            }
                                            else
                                            {
                                                #region 面积计算情况

                                                HtmlNode zyqk = cell.SelectNodes("table/tr/td")[2];//错误情况

                                                if (zyqk.InnerText != "")
                                                {
                                                    foreach (string key in dic_message_mjjs.Keys)
                                                    {
                                                        string zymjPfm = Regex.Match(zyqk.InnerText, "[0-9]*[.]?[0-9]*平方米").Value;

                                                        if (row.ChildNodes[0].InnerText.Contains(key) && zymjPfm != "")
                                                        {
                                                            decimal temp = 0;

                                                            decimal.TryParse(zymjPfm.Substring(0, zymjPfm.Length - 3), out temp);

                                                            if (isAgreeRegexSecond == true && (key.StartsWith("规划底图") || key.StartsWith("基本农田图层")))
                                                            {
                                                                //二次规划验证通过了,不在显示这两个类型的 面积
                                                            }
                                                            else if (key.StartsWith("规划底图") && temp < 16)
                                                            {
                                                                //规划相关需大于等于16平米 才显示
                                                            }
                                                            else
                                                            {
                                                                dic_message_mjjs[key] += temp;
                                                            }

                                                            break;
                                                        }
                                                    }

                                                }
                                                #endregion
                                            }

                                            break;
                                        }
                                    }

                                }

                            }
                        }

                    }

                }


                List<string> l_keywords = new List<string>();
                l_keywords.Add("占压");
                l_keywords.Add("缺失");
                l_keywords.Add("不符");

                foreach (string key in dic_message_mjjs.Keys)
                {
                    if (dic_message_mjjs[key] != 0)
                    {
                        double mj = Eva.Library.Text.NumberTool.Round(double.Parse(dic_message_mjjs[key].ToString()), 1);

                        if (mj == 0)
                        {
                            continue;
                        }

                        foreach (string keyword in l_keywords)
                        {
                            if (key.Contains(keyword))
                            {
                                l_message.Add(key + "" + keyword + "面积:" + mj.ToString() + "平方米" + "" + (decimal.Parse(mj.ToString()) / 10000).ToString() + "公顷)");

                                break;
                            }
                        }

                    }
                }



                Dictionary<string, string> dicRes = new Dictionary<string, string>();
                dicRes.Add("errorSysId", string.Join("^", l_errormessageSysId));
                dicRes.Add("errormessage", string.Join("<br/>", l_message));


                resultDic["result"] = "true";
                resultDic["message"] = Eva.Library.Format.FormatEntityTool.FormatDicToJson(dicRes);

            }
            catch (Exception ex)
            {
                resultDic["result"] = "false";
                resultDic["message"] = Eva.Library.Format.FormatTextTool.ErrorMessageFormat(ex.Message + ex.StackTrace);
            }
            return Eva.Library.Format.FormatEntityTool.FormatDicToJson(resultDic);
        }
View Code

 

2. C# 对XML的格式化

private string FormatXml(string sUnformattedXml)  
     {  
         XmlDocument xd = new XmlDocument();  
         xd.LoadXml(sUnformattedXml);  
         StringBuilder sb = new StringBuilder();  
         StringWriter sw = new StringWriter(sb);  
         XmlTextWriter xtw = null;  
         try  
         {  
             xtw = new XmlTextWriter(sw);  
             xtw.Formatting = Formatting.Indented;  
             xtw.Indentation = 1;  
             xtw.IndentChar = '\t';  
             xd.WriteTo(xtw);  
         }  
         finally  
         {  
             if (xtw != null)  
                 xtw.Close();  
         }  
         return sb.ToString();  
     }  
View Code

  

十、配置文件操作

C#-数据库连接

    <!--sql 数据库-->
    <add key="DataType" value="sql"/>
    <add key="connStr" value="server=LIHY-PC\MSSQLSERVER2012;database=Microelec;uid=sa;pwd=li12850"/>
    

    <!--oracle 数据库-->
    <add key="DataType" value="orcl"/>
    <add key="connStr" value="Data Source=orcl;user id=vdz;password=li12850"/>
View Code

 

C#-Config文件加节点及读取方法

app.config中<ColorGroup>节点组

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <configSections>
    <sectionGroup name="ColorGroup">
      <section name="BackGroundColor" type="System.Configuration.NameValueSectionHandler"/>
    </sectionGroup> 
  </configSections>

  <appSettings>
  </appSettings>


  <ColorGroup>
    <BackGroundColor>
      <add key ="Red" value="187"/>
      <add key ="Green" value="206"/>
      <add key ="Blue" value="230"/>
    </BackGroundColor>
  </ColorGroup>
</configuration>





.cs文件中读取

  /// <summary>
        /// 背景颜色
        /// </summary>
        static public Color BackGroundColor
        {
            get
            {
                NameValueCollection config = (NameValueCollection)ConfigurationManager.GetSection("ColorGroup/BackGroundColor");

                int red = int.Parse(config["Red"].ToString());
                int green = int.Parse(config["Green"].ToString());
                int blue = int.Parse(config["Blue"].ToString());

                Color c = Color.FromArgb(red, green, blue);

                return c;
            }
        }
View Code

 

 C#-appconfig配置

数据库连接
<configuration>
  <connectionStrings> 
    <add name ="orclConnectionString" connectionString="Data source=orcl110;user id=vdz; password=li12850" providerName="System.Data.OracleClient"/> 
  </connectionStrings>
</configuration>




<add key="38_LogConnectionString" value="user id=EasyServiceLog_SPTJ;data source=gis13;password=JYDPADlNSNKjRNu2c7Wj4qeclxkKuwK0"/>
View Code

  

C#-读取指定的Config配置文件

        ExeConfigurationFileMap map = new ExeConfigurationFileMap();
            map.ExeConfigFilename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web1.config");
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            string connstr = config.ConnectionStrings.ConnectionStrings["name"].ConnectionString;
            string key = config.AppSettings.Settings["key"].Value;



js 读取 config

原https://blog.csdn.net/younghaiqing/article/details/71211324
在js文件中,获取webconfig中的配置信息
置顶 2017年05月05日 15:15:24 younghaiqing 阅读数:9697
webconfig中的配置信息
    <!--默认押金-->
    <add key="OverDueMoney" value="80" />
1
2
1.在客户端页面(非单独的js文件),可以直接获取webconfig的配置信息
function Name() {
var Name=System.Web.Configuration.WebConfigurationManager.AppSettings["OverDueMoney"];
}
1
2
3
2.在单独的js文件中,那该如何调用Webconfig?
2.1在前段页面中,可以直接自定个标签
  <input class="easyui-textbox" default-price="0" default-subsidies="0" type="text" default-value="<%=ConfigurationManager.AppSettings.AllKeys.Contains("OverDueMoney")%>"
                                    name="OtherPrice" id="OtherPrice" />
1
2
3
2.2在js页面中,通过attr获取属性里面绑定的值
 var OverDueMoney = $("#OtherPrice").attr("default-value");
View Code

 

Mvc序列化大小写

序列序后端传到前端字段大小写 netcore中 statpup.cs 

services.AddMvc().AddJsonOptions(op => op.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver());//序列化保持原有大小写(默认首字母小写)
View Code

 

  

  

 

十一、其他操作

C#-ping ip地址

 /// <summary>
        /// ping ip地址
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public bool Ping(string ip)
        {

            System.Net.NetworkInformation.Ping p = new System.Net.NetworkInformation.Ping();

            System.Net.NetworkInformation.PingOptions options = new System.Net.NetworkInformation.PingOptions();

            options.DontFragment = true;

            string data = "Test Data!";

            byte[] buffer = Encoding.ASCII.GetBytes(data);

            int timeout = 1000; // Timeout 时间,单位:毫秒

            System.Net.NetworkInformation.PingReply reply = p.Send(ip, timeout, buffer, options);

            if (reply.Status == System.Net.NetworkInformation.IPStatus.Success)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
View Code

 

C#-查找当前IP地址

   /// <summary>
        /// 返回IP地址
        /// </summary>
        /// <returns></returns>
        public string IP_return()
        {
            string strHostIP = "";
            IPHostEntry oIPHost = Dns.Resolve(Environment.MachineName);
            if (oIPHost.AddressList.Length > 0)
            {
                strHostIP = oIPHost.AddressList[0].ToString();
            }
            return strHostIP;
        }
View Code

  

C#-复制数据到剪切板

  class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            string textData = "LlyscYsykrYqqlmGsycl$1";
            bool autoConvert = true;

            DataObject data = new DataObject(DataFormats.UnicodeText, (Object)textData, autoConvert);


            //如果应用程序退出时要将数据保留在系统剪贴板中,则为 true;如果应用程序退出时要将数据从系统剪贴板中清除,则为 false。
            Clipboard.SetDataObject(data, true);

            //bool isOriginalDataObject = Clipboard.IsCurrent(data);
        }
    }
View Code

 

 C#-获取当前命名空间,类名,方法名的方法

Asp.net .net(C#) 获取当前命名空间,类名,方法名的方法

以下方法在即时窗口中不能使用, 请各位大大们调试的时候注意了!

可以直接写在方法中输出来看看哦!
 
public static string GetMethodInfo()
{
    string str = "";  
    //取得当前方法命名空间
    str += "命名空间名:"+System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace + "\n";
    //取得当前方法类全名 包括命名空间
    str += "类名:"+System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "\n";
    //取得当前方法名
    str += "方法名:"+System.Reflection.MethodBase.GetCurrentMethod().Name + "\n";
    str += "\n";     
 
    StackTrace ss = new StackTrace(true);
    MethodBase mb = ss.GetFrame(1).GetMethod();
    //取得父方法命名空间
    str += mb.DeclaringType.Namespace + "\n";
    //取得父方法类名
    str += mb.DeclaringType.Name + "\n";
    //取得父方法类全名
    str += mb.DeclaringType.FullName + "\n";
    //取得父方法名
    str += mb.Name + "\n";
    return str;
}
 
public static void Main()
{
    Console.WriteLine(GetMethodInfo());
 
    Console.ReadKey();
}
View Code

 

posted @ 2020-07-09 14:58  无心々菜  阅读(287)  评论(0编辑  收藏  举报