服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C# 常用公共方法

C# 常用公共方法

2021-12-01 14:45码农-小菜鸟 C#

这篇文章主要为大家详细介绍了C# 常用公共方法,分享给大家,供大家参考,感兴趣的小伙伴们可以参考一下

C# 常用公共方法,具体内容如下

1.后台调用weburl

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
string hostUrl = "http://www.a.com?id=123" ;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(hostUrl);
myReq.Method = "GET";
 
HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
Stream myStream = HttpWResp.GetResponseStream();
StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
StringBuilder strBuilder = new StringBuilder();
while (-1 != sr.Peek())
{
strBuilder.Append(sr.ReadLine());
}
sr.Close();
myStream.Close();
HttpWResp.Close();
 
Newtonsoft.Json.Linq.JObject jo = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(strBuilder.ToString());
string resCode = jo["ReturnCode"].ToString();

2.检测输入URL是否合法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/// <summary>
 /// 判断网址是否可以访问
 /// </summary>
 /// <param name="Url"></param>
 /// <returns></returns>
 protected bool ChkPageUrl(string url)
 {
  bool result = false;
  try
  {
   HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
   myHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
   myHttpWebRequest.Method = "GET";
   HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
   if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
   {
    result = true;
   }
   myHttpWebResponse.Close();
  }
  catch
  {
   result = false;
  }
 
  return result;
 }

3.批量导出

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/// <summary>
 /// 批量导出
 /// </summary>
 /// <returns></returns>
 public FileResult ExportStu()
 {
  //创建Excel文件的对象
  NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
  //添加一个sheet
  NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
  int pager_totalcount = (int)Session["pager_totalcount"];
  int totalCount = 0;
  //获取list数据
  List<ArticleEntity> infoList = new AchieveDAL.MyTestDAL().GetArticleList("", pager_totalcount, 1, out totalCount);
 
  //给sheet1添加第一行的头部标题
  NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
  //创建时间 名称 商户订单号 | 交易号 对方 金额(元) 状态
  row1.CreateCell(0).SetCellValue("编号");
  row1.CreateCell(1).SetCellValue("标题");
  row1.CreateCell(2).SetCellValue("内容");
  int Width = 256;
  sheet1.SetColumnWidth(0, 10 * Width);
  sheet1.SetColumnWidth(1, 25 * Width);
  sheet1.SetColumnWidth(2, 60 * Width);
  if (infoList != null)
  {
   var list = infoList.OrderByDescending(p => p.ID);
 
   if (list != null)
   {
    int i = 0;
    //将数据逐步写入sheet1各个行
    foreach (var item in list)
    {
     i = i + 1;
     NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i);
     rowtemp.CreateCell(0).SetCellValue(item.ID.ToString());
     rowtemp.CreateCell(1).SetCellValue(item.Title == null ? "" : item.Title.ToString());
     rowtemp.CreateCell(2).SetCellValue(item.Content == null ? "" : item.Content.ToString());
    }
   }
  }
  // 写入到客户端
  System.IO.MemoryStream ms = new System.IO.MemoryStream();
  book.Write(ms);
  ms.Seek(0, System.IO.SeekOrigin.Begin);
  return File(ms, "application/vnd.ms-excel", HttpUtility.UrlEncode("导出", Encoding.UTF8).ToString() + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
 
 }

4.批量导入

 <input name="file" type="file" id="file" />
<input type="submit" name="Upload" value="上传" />

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/// <summary>
  /// 批量导入
  /// </summary>
  /// <returns></returns>
  [HttpPost]
  public ActionResult ImportStu()
  {
   HttpPostedFileBase file = Request.Files["file"];
   string FileName;
   string savePath;
   if (file == null || file.ContentLength <= 0)
   {
    return Content("<script>alert('上传失败,请选择上传文件!');location.href='/MyTest/MVCPager';</script>");
   }
   else
   {
    string filename = Path.GetFileName(file.FileName);
    int filesize = file.ContentLength;//获取上传文件的大小单位为字节byte
    string fileEx = System.IO.Path.GetExtension(filename);//获取上传文件的扩展名
    string NoFileName = System.IO.Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
    string FileType = ".xls,.xlsx";//定义上传文件的类型字符串
    if (FileType.Contains(".exe"))//EXCEL
    {
     return Content("<script>alert('上传文件类型格式错误,不允许导入exe格式的文件!');location.href='/MyTest/MVCPager';</script>");
    }
    FileName = NoFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx;
    string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
    savePath = Path.Combine(path, FileName);
    file.SaveAs(savePath);
 
    if (FileType.Contains(fileEx))//EXCEL
    {
     string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + savePath + ";" + "Extended Properties=Excel 8.0";
     OleDbConnection conn = new OleDbConnection(strConn);
     conn.Open();
     OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$]", strConn);
     DataSet myDataSet = new DataSet();
     try
     {
      myCommand.Fill(myDataSet, "ExcelInfo");
     }
     catch (Exception ex)
     {
      return Content("<script>alert('上传失败," + ex.Message + "!');location.href='/MyTest/MVCPager';</script>");
     }
     //列顺序 标题 内容
     DataTable table = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable();
 
     //事物 异常回滚
     using (TransactionScope transaction = new TransactionScope())
     {
      for (int i = 0; i < table.Rows.Count; i++)
      {
       ArticleEntity model = new ArticleEntity();
       model.Title = table.Rows[i][0].ToString();
       model.Content = table.Rows[i][1].ToString();
       new AchieveDAL.MyTestDAL().AddArticle(model);
      }
      transaction.Complete();
     }
    }
 
    return RedirectToAction("MVCPager", "MyTest");
   }
  }

5.获取客户端的IP地址

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/// <summary>
  /// 获取客户端的IP地址
  /// </summary>
  /// <returns>客户端IP地址</returns>
  public static string Get_ClientIP()
  {
   string result = string.Empty;
   result = HttpContext.Current.Request.Headers["X-Real-IP"]; //Nginx 为前端时获取IP地址的方法
   if (result != null)
    return result;
 
   if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)//发出请求的远程主机的IP地址
   {
    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
   }
   else if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)//判断是否设置代理,若使用了代理
   {
    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)//获取代理服务器的IP
    {
     result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    }
    else
    {
     result = HttpContext.Current.Request.UserHostAddress;
    }
   }
   else
   {
    result = HttpContext.Current.Request.UserHostAddress;
   }
   if (result == "::1")
    result = string.Empty;
   return result;
  }

6.AES对称加密

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
/// <summary>
/// 对称加密类
/// </summary>
public class AES
{
 /// <summary>
 /// 解密
 /// </summary>
 /// <param name="strDecrypt"></param>
 /// <param name="strKey"></param>
 /// <returns></returns>
 public static string Decrypt(string strDecrypt, string strKey)
 {
  try
  {
   byte[] bytes = Encoding.UTF8.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(strKey, "md5"));
   byte[] inputBuffer = Convert.FromBase64String(strDecrypt);
   byte[] buffer3 = null;
   using (RijndaelManaged managed = new RijndaelManaged())
   {
    managed.Key = bytes;
    managed.Mode = CipherMode.ECB;
    managed.Padding = PaddingMode.PKCS7;
    buffer3 = managed.CreateDecryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
   }
   return Encoding.UTF8.GetString(buffer3);
  }
  catch
  {
   return null;
  }
 }
 
 /// <summary>
 /// 解密
 /// </summary>
 /// <param name="strDecrypt"></param>
 /// <param name="strKey"></param>
 /// <returns></returns>
 public static string Decrypt(string toDecrypt, string key, string iv)
 {
  byte[] bytes = Encoding.UTF8.GetBytes(key);
  byte[] buffer2 = Encoding.UTF8.GetBytes(iv);
  byte[] inputBuffer = Convert.FromBase64String(toDecrypt);
  RijndaelManaged managed = new RijndaelManaged
  {
   Key = bytes,
   IV = buffer2,
   Mode = CipherMode.CBC,
   Padding = PaddingMode.Zeros
  };
  byte[] buffer4 = managed.CreateDecryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
  return Encoding.UTF8.GetString(buffer4);
 }
 
 public static string DecryptStr(string EncryptString)
 {
  string str = "";
  if (!string.IsNullOrEmpty(EncryptString))
  {
   string sSource = Decrypt(EncryptString, "cn.solefu");
   if (Utility.Left(sSource, 3) == "gk_")
   {
    str = sSource.Substring(3);
   }
  }
  return str;
 }
 
 public static string DecryptStrByCBC(string EncryptString)
 {
  string str = "";
  if (!string.IsNullOrEmpty(EncryptString))
  {
   string sSource = Decrypt(EncryptString, "cn.solefu", "cn.solefu");
   if (Utility.Left(sSource, 3) == "gk_")
   {
    str = sSource.Substring(3);
   }
  }
  return str;
 }
 
 /// <summary>
 /// 加密
 /// </summary>
 /// <param name="strEncrypt"></param>
 /// <param name="strKey"></param>
 /// <returns></returns>
 public static string Encrypt(string strEncrypt, string strKey)
 {
  try
  {
   byte[] bytes = Encoding.UTF8.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(strKey, "md5"));
   byte[] inputBuffer = Encoding.UTF8.GetBytes(strEncrypt);
   byte[] inArray = null;
   using (RijndaelManaged managed = new RijndaelManaged())
   {
    managed.Key = bytes;
    managed.Mode = CipherMode.ECB;
    managed.Padding = PaddingMode.PKCS7;
    inArray = managed.CreateEncryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
   }
   return Convert.ToBase64String(inArray, 0, inArray.Length);
  }
  catch
  {
   return null;
  }
 }
 
 /// <summary>
 /// 加密
 /// </summary>
 /// <param name="strEncrypt"></param>
 /// <param name="strKey"></param>
 /// <returns></returns>
 public static string Encrypt(string toEncrypt, string key, string iv)
 {
  byte[] bytes = Encoding.UTF8.GetBytes(key);
  byte[] buffer2 = Encoding.UTF8.GetBytes(iv);
  byte[] inputBuffer = Encoding.UTF8.GetBytes(toEncrypt);
  RijndaelManaged managed = new RijndaelManaged
  {
   Key = bytes,
   IV = buffer2,
   Mode = CipherMode.CBC,
   Padding = PaddingMode.Zeros
  };
  byte[] inArray = managed.CreateEncryptor().TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
  return Convert.ToBase64String(inArray, 0, inArray.Length);
 }
 
 public static string EncryptStr(string SourceString)
 {
  return Encrypt("gk_" + SourceString, "cn.solefu");
 }
 
 public static string EncryptStr(string SourceString, bool UseInUrl)
 {
  return HttpUtility.UrlEncode(EncryptStr(SourceString));
 }
 
 public static string EncryptStrByCBC(string SourceString)
 {
  return Encrypt("gk_" + SourceString, "cn.solefu", "cn.solefu");
 }
 
 public static string EncryptStrByCBC(string SourceString, bool UseInUrl)
 {
  return HttpUtility.UrlEncode(EncryptStrByCBC(SourceString));
 }
}

7.Cookies帮助类

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
public class CookiesHelper
 {
  public static void AddCookie(string cookieName, DateTime expires)
  {
   HttpCookie cookie = new HttpCookie(cookieName)
   {
    Expires = expires
   };
   AddCookie(cookie, null);
  }
 
  public static void AddCookie(string key, string value)
  {
   AddCookie(new HttpCookie(key, value), null);
  }
 
  public static void AddCookie(HttpCookie cookie, string Domain)
  {
   HttpResponse response = HttpContext.Current.Response;
   if (response != null)
   {
    cookie.HttpOnly = true;
    cookie.Path = "/";
    if (!string.IsNullOrEmpty(Domain))
    {
     cookie.Domain = Domain;
    }
    response.AppendCookie(cookie);
   }
  }
 
  public static void AddCookie(string cookieName, DateTime expires, string Domain)
  {
   HttpCookie cookie = new HttpCookie(cookieName)
   {
    Expires = expires
   };
   AddCookie(cookie, Domain);
  }
 
  public static void AddCookie(string key, string value, DateTime expires)
  {
   HttpCookie cookie = new HttpCookie(key, value)
   {
    Expires = expires
   };
   AddCookie(cookie, null);
  }
 
  public static void AddCookie(string cookieName, string key, string value)
  {
   HttpCookie cookie = new HttpCookie(cookieName);
   cookie.Values.Add(key, value);
   AddCookie(cookie, null);
  }
 
  public static void AddCookie(string key, string value, bool withDomain, string Domain)
  {
   if (withDomain)
   {
    AddCookie(new HttpCookie(key, value), Domain);
   }
   else
   {
    AddCookie(new HttpCookie(key, value), null);
   }
  }
 
  public static void AddCookie(string key, string value, DateTime expires, string Domain)
  {
   HttpCookie cookie = new HttpCookie(key, value)
   {
    Expires = expires
   };
   AddCookie(cookie, Domain);
  }
 
  public static void AddCookie(string cookieName, string key, string value, DateTime expires)
  {
   HttpCookie cookie = new HttpCookie(cookieName)
   {
    Expires = expires
   };
   cookie.Values.Add(key, value);
   AddCookie(cookie, null);
  }
 
  public static void AddCookie(string cookieName, string key, string value, string Domain)
  {
   HttpCookie cookie = new HttpCookie(cookieName);
   cookie.Values.Add(key, value);
   AddCookie(cookie, Domain);
  }
 
  public static void AddCookie(string cookieName, string key, string value, DateTime expires, string Domain)
  {
   HttpCookie cookie = new HttpCookie(cookieName)
   {
    Expires = expires
   };
   cookie.Values.Add(key, value);
   AddCookie(cookie, Domain);
  }
 
  public static void AddDomainCookie(string key, string value, string Domain)
  {
   AddCookie(new HttpCookie(key, value), Domain);
  }
 
  public static HttpCookie GetCookie(string cookieName)
  {
   HttpRequest request = HttpContext.Current.Request;
   if (request != null)
   {
    if (request.Cookies[cookieName] != null)
    {
     return request.Cookies[cookieName];
    }
    if (request.Cookies[", " + cookieName] != null)
    {
     return request.Cookies[", " + cookieName];
    }
   }
   return null;
  }
 
  public static string GetCookieValue(string cookieName)
  {
   return GetCookieValue(cookieName, null);
  }
 
  public static string GetCookieValue(string cookieName, string key)
  {
   HttpRequest request = HttpContext.Current.Request;
   if (request == null)
   {
    return "";
   }
   if (request.Cookies[cookieName] != null)
   {
    if (!string.IsNullOrEmpty(key) && request.Cookies[cookieName].HasKeys)
    {
     return request.Cookies[cookieName].Values[key];
    }
    return request.Cookies[cookieName].Value;
   }
   string str = ", " + cookieName;
   if (request.Cookies[str] == null)
   {
    return "";
   }
   if (!string.IsNullOrEmpty(key) && request.Cookies[str].HasKeys)
   {
    return request.Cookies[str].Values[key];
   }
   return request.Cookies[str].Value;
  }
 
  public static string GetCookieValue(HttpCookie cookie, string key)
  {
   if (cookie == null)
   {
    return "";
   }
   if (!string.IsNullOrEmpty(key) && cookie.HasKeys)
   {
    return cookie.Values[key];
   }
   return cookie.Value;
  }
 
  public static void RemoveCookie(string cookieName)
  {
   RemoveCookie(cookieName, null);
  }
 
  public static void RemoveCookie(string cookieName, string key)
  {
   HttpResponse response = HttpContext.Current.Response;
   if (response != null)
   {
    HttpCookie cookie = response.Cookies[cookieName];
    if (cookie != null)
    {
     if (!string.IsNullOrEmpty(key) && cookie.HasKeys)
     {
      cookie.Values.Remove(key);
     }
     else
     {
      response.Cookies.Remove(cookieName);
     }
    }
   }
  }
 
  public static void SetCookie(string cookieName, DateTime expires)
  {
   SetCookie(cookieName, null, null, new DateTime?(expires), null);
  }
 
  public static void SetCookie(string key, string value)
  {
   SetCookie(key, null, value, null, null);
  }
 
  public static void SetCookie(string cookieName, DateTime expires, string Domain)
  {
   SetCookie(cookieName, null, null, new DateTime?(expires), Domain);
  }
 
  public static void SetCookie(string key, string value, DateTime expires)
  {
   SetCookie(key, null, value, new DateTime?(expires), null);
  }
 
  public static void SetCookie(string cookieName, string key, string value)
  {
   SetCookie(cookieName, key, value, null, null);
  }
 
  public static void SetCookie(string key, string value, bool withDomain, string Domain)
  {
   if (withDomain)
   {
    SetCookie(key, null, value, null, Domain);
   }
   else
   {
    SetCookie(key, null, value, null, null);
   }
  }
 
  public static void SetCookie(string key, string value, DateTime expires, string Domain)
  {
   SetCookie(key, null, value, new DateTime?(expires), Domain);
  }
 
  public static void SetCookie(string cookieName, string key, string value, string Domain)
  {
   SetCookie(cookieName, key, value, null, Domain);
  }
 
  public static void SetCookie(string cookieName, string key, string value, DateTime? expires, string Domain)
  {
   HttpResponse response = HttpContext.Current.Response;
   if (response != null)
   {
    HttpCookie cookie = response.Cookies[cookieName];
    if (cookie != null)
    {
     cookie.Path = "/";
     if (!string.IsNullOrEmpty(Domain))
     {
      cookie.Domain = Domain;
     }
     if (!string.IsNullOrEmpty(key) && cookie.HasKeys)
     {
      cookie.Values.Set(key, value);
     }
     else if (!string.IsNullOrEmpty(value))
     {
      cookie.Value = value;
     }
     if (expires.HasValue)
     {
      cookie.Expires = expires.Value;
     }
     response.SetCookie(cookie);
    }
   }
  }
  /// <summary>
  /// 设置域的cookie
  /// </summary>
  /// <param name="key"></param>
  /// <param name="value"></param>
  /// <param name="Domain"></param>
  public static void SetDomainCookie(string key, string value, string Domain)
  {
   SetCookie(key, null, value, null, Domain);
  }
 }

8.DataTable转换成实体类

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
/// <summary>
/// #region DataTable转换成实体类
/// </summary>
/// <typeparam name="T"></typeparam>
public class ModelUtil<T> where T : new()
{
 
 /// <summary>
 /// 填充对象列表:用DataSet的第一个表填充实体类
 /// </summary>
 /// <param name="ds">DataSet</param>
 /// <returns></returns>
 public static List<T> FillModel(DataSet ds)
 {
  if (ds == null || ds.Tables[0] == null || ds.Tables[0].Rows.Count == 0)
  {
   return null;
  }
  else
  {
   return FillModel(ds.Tables[0]);
  }
 }
 
 /// <summary>
 /// 填充对象列表:用DataSet的第index个表填充实体类
 /// </summary>
 public static List<T> FillModel(DataSet ds, int index)
 {
  if (ds == null || ds.Tables.Count <= index || ds.Tables[index].Rows.Count == 0)
  {
   return null;
  }
  else
  {
   return FillModel(ds.Tables[index]);
  }
 }
 
 /// <summary>
 /// 填充对象列表:用DataTable填充实体类
 /// </summary>
 public static List<T> FillModel(DataTable dt)
 {
  if (dt == null || dt.Rows.Count == 0)
  {
   return null;
  }
  List<T> modelList = new List<T>();
  foreach (DataRow dr in dt.Rows)
  {
   //T model = (T)Activator.CreateInstance(typeof(T));
   T model = new T();
   for (int i = 0; i < dr.Table.Columns.Count; i++)
   {
    List<PropertyInfo> propertyInfos = model.GetType().GetProperties().ToList();
 
    PropertyInfo item = propertyInfos.FirstOrDefault(p => string.Compare(p.Name, dr.Table.Columns[i].ColumnName, true) == 0);
    if (item != null && dr[i] != DBNull.Value)
     try
     {
      item.SetValue(model, dr[i], null);
     }
     catch
     {
     }
   }
 
   modelList.Add(model);
  }
  return modelList;
 }
 
 /// <summary>
 /// 填充对象:用DataRow填充实体类
 /// </summary>
 public static T FillModel(DataRow dr)
 {
  if (dr == null)
  {
   return default(T);
  }
 
  //T model = (T)Activator.CreateInstance(typeof(T));
  T model = new T();
 
  for (int i = 0; i < dr.Table.Columns.Count; i++)
  {
   List<PropertyInfo> propertyInfos = model.GetType().GetProperties().ToList();
 
   PropertyInfo item = propertyInfos.FirstOrDefault(p => string.Compare(p.Name, dr.Table.Columns[i].ColumnName, true) == 0);
   if (item != null && dr[i] != DBNull.Value)
    try
    {
     item.SetValue(model, dr[i], null);
    }
    catch
    {
    }
  }
  return model;
 }
 
 
 /// <summary>
 /// 实体类转换成DataSet
 /// </summary>
 /// <param name="modelList">实体类列表</param>
 /// <returns></returns>
 public static DataSet FillDataSet(List<T> modelList)
 {
  if (modelList == null || modelList.Count == 0)
  {
   return null;
  }
  else
  {
   DataSet ds = new DataSet();
   ds.Tables.Add(FillDataTable(modelList));
   return ds;
  }
 }
 
 /// <summary>
 /// 实体类转换成DataTable
 /// </summary>
 /// <param name="modelList">实体类列表</param>
 /// <returns></returns>
 public static DataTable FillDataTable(List<T> modelList)
 {
  if (modelList == null || modelList.Count == 0)
  {
   return null;
  }
  DataTable dt = CreateData(modelList[0]);
 
  foreach (T model in modelList)
  {
   DataRow dataRow = dt.NewRow();
   foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
   {
    dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
   }
   dt.Rows.Add(dataRow);
  }
  return dt;
 }
 
 /// <summary>
 /// 根据实体类得到表结构
 /// </summary>
 /// <param name="model">实体类</param>
 /// <returns></returns>
 private static DataTable CreateData(T model)
 {
  DataTable dataTable = new DataTable(typeof(T).Name);
  foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
  {
   dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
  }
  return dataTable;
 }
 
 /// <summary>
 /// 将DataTable以转为List与Dictionary嵌套集合保存
 /// </summary>
 /// <param name="dt"></param>
 /// <returns></returns>
 public static List<Dictionary<string, string>> ToListDictionary(DataTable dt)
 {
  List<Dictionary<string, string>> list = null;
  if (dt != null && dt.Rows.Count > 0)
  {
   list = new List<Dictionary<string, string>>();
   Dictionary<string, string> dic = null;
   foreach (DataRow dr in dt.Rows)
   {
    dic = new Dictionary<string, string>();
    foreach (DataColumn dc in dt.Columns)
    {
     dic.Add(dc.ColumnName, dr[dc.ColumnName].ToString());
    }
    list.Add(dic);
   }
  }
  return list;
 }
 
 /// <summary>
 /// 请求的request的内容转换为model
 /// cza
 /// 2016-5-30 19:06:21
 /// </summary>
 /// <param name="context"></param>
 /// <returns></returns>
 public static T ConvertToModel(HttpContext context)
 {
  T t = new T();
  PropertyInfo[] propertys = t.GetType().GetProperties();
  foreach (PropertyInfo pi in propertys)
  {
   if (!pi.CanWrite)
    continue;
   object value = context.Request[pi.Name];
   if (value != null && value != DBNull.Value)
   {
    try
    {
     if (value.ToString() != "")
      pi.SetValue(t, Convert.ChangeType(value, pi.PropertyType), null);//这一步很重要,用于类型转换
     else
      pi.SetValue(t, value, null);
    }
    catch
    { }
   }
  }
 
  return t;
 }
 
 
}

9.SQL Server数据库访问类

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/// <summary>
/// SQL Server数据库访问类
/// </summary>
public abstract class SqlHelper
{
 //读取配置文件里的数据库连接字符串
 public static readonly string connStr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
 
 //空构造
 public SqlHelper() { }
 
 //Hashtable to store cached parameters
 private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
 
 /// <summary>
 /// 执行增删改【常用】
 /// </summary>
 public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras)
 {
  SqlCommand cmd = new SqlCommand();
  using (SqlConnection conn = new SqlConnection(connectionString))
  {
   PrepareCommand(cmd, conn, null, commandType, commandText, paras);
   int val = cmd.ExecuteNonQuery();
   cmd.Parameters.Clear();   //清空参数
   return val;
  }
 }
 
 /// <summary>
 /// 执行增删改(对现有的数据库连接)【不常用】
 /// </summary>
 public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] paras)
 {
  SqlCommand cmd = new SqlCommand();
  PrepareCommand(cmd, connection, null, commandType, commandText, paras);
  int val = cmd.ExecuteNonQuery();
  cmd.Parameters.Clear();
  return val;
 }
 
 /// <summary>
 /// 执行多条sql语句(List泛型集合)【事务】(无参数)
 /// </summary>
 /// <param name="connectionString">数据库连接字符串</param>
 /// <param name="listSql">包含多条sql语句的泛型集合</param>
 /// <returns>受影响行数</returns>
 public static int ExecuteNonQuery(string connectionString, List<string> listSql)
 {
  SqlCommand cmd = new SqlCommand();
  SqlConnection conn = new SqlConnection(connectionString);
  conn.Open();
  SqlTransaction trans = conn.BeginTransaction();
  PrepareCommand(cmd, conn, trans, CommandType.Text, null, null);
  try
  {
   int count = 0;
   for (int n = 0; n < listSql.Count; n++)
   {
    string strSql = listSql[n];
    if (strSql.Trim().Length > 1)
    {
     cmd.CommandText = strSql;
     count += cmd.ExecuteNonQuery();
    }
   }
   trans.Commit();
   cmd.Parameters.Clear();
   return count;
  }
  catch
  {
   trans.Rollback();
   cmd.Parameters.Clear();
   return 0;
  }
  finally
  {
   conn.Close();
  }
 }
 
 /// <summary>
 /// 执行多条sql语句(Hashtable)【事务】(带一组参数,一个参数也得封装成组)
 /// </summary>
 /// <param name="connectionString">数据库连接字符串</param>
 /// <param name="sqlStringList">Hashtable表,键值对形式</param>
 public static void ExecuteNonQuery(string connectionString, Hashtable sqlStringList)
 {
  using (SqlConnection conn = new SqlConnection(connectionString))
  {
   conn.Open();
   using (SqlTransaction trans = conn.BeginTransaction())
   {
    SqlCommand cmd = new SqlCommand();
    try
    {
     foreach (DictionaryEntry item in sqlStringList)
     {
      string cmdText = item.Key.ToString(); //要执行的sql语句
      SqlParameter[] cmdParas = (SqlParameter[])item.Value; //sql语句对应的参数
      PrepareCommand(cmd, conn, trans, CommandType.Text, cmdText, cmdParas);
      int val = cmd.ExecuteNonQuery();
      cmd.Parameters.Clear();
     }
     if (sqlStringList.Count > 0)
      trans.Commit();
    }
    catch
    {
     trans.Rollback();
     throw;
    }
   }
  }
 
 }
 
 /// <summary>
 /// 返回DataReader对象
 /// </summary>
 public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string cmdText, params SqlParameter[] paras)
 {
  SqlCommand cmd = new SqlCommand();
  SqlConnection conn = new SqlConnection(connectionString);
  try
  {
   PrepareCommand(cmd, conn, null, commandType, cmdText, paras);
   SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
   cmd.Parameters.Clear();
   return reader;
  }
  catch
  {
   conn.Close();
   throw;
  }
 }
 
 /// <summary>
 /// 返回第一行第一列信息(可能是字符串 所以返回类型是object)【常用】
 /// </summary>
 public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras)
 {
  SqlCommand cmd = new SqlCommand();
  using (SqlConnection connection = new SqlConnection(connectionString))
  {
   PrepareCommand(cmd, connection, null, commandType, commandText, paras);
   object val = cmd.ExecuteScalar();
   cmd.Parameters.Clear();
   return val;
  }
 }
 
 /// <summary>
 /// 返回第一行第一列信息(针对现有的数据库连接)【不常用】
 /// </summary>
 public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] paras)
 {
  SqlCommand cmd = new SqlCommand();
 
  PrepareCommand(cmd, connection, null, commandType, commandText, paras);
  object val = cmd.ExecuteScalar();
  cmd.Parameters.Clear();
  return val;
 }
 
 /// <summary>
 /// 返回DataTable
 /// </summary>
 public static DataTable GetDataTable(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras)
 {
  SqlCommand cmd = new SqlCommand();
  using (SqlConnection conn = new SqlConnection(connectionString))
  {
   PrepareCommand(cmd, conn, null, commandType, commandText, paras);
   using (SqlDataAdapter da = new SqlDataAdapter(cmd))
   {
    DataTable dt = new DataTable();
    da.Fill(dt);
    return dt;
   }
  }
 }
 
 /// <summary>
 /// 返回DataSet
 /// </summary>
 public static DataSet GetDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras)
 {
  SqlCommand cmd = new SqlCommand();
  using (SqlConnection conn = new SqlConnection(connectionString))
  {
   PrepareCommand(cmd, conn, null, commandType, commandText, paras);
   using (SqlDataAdapter da = new SqlDataAdapter(cmd))
   {
    DataSet ds = new DataSet();
    da.Fill(ds);
    return ds;
   }
  }
 }
 
 /// <summary>
 /// add parameter array to the cache
 /// </summary>
 /// <param name="cacheKey">Key to the parameter cache</param>
 /// <param name="cmdParms">an array of SqlParamters to be cached</param>
 public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
 {
  parmCache[cacheKey] = commandParameters;
 }
 
 /// <summary>
 /// Retrieve cached parameters
 /// </summary>
 /// <param name="cacheKey">key used to lookup parameters</param>
 /// <returns>Cached SqlParamters array</returns>
 public static SqlParameter[] GetCachedParameters(string cacheKey)
 {
  SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];
 
  if (cachedParms == null)
   return null;
 
  SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];
 
  for (int i = 0, j = cachedParms.Length; i < j; i++)
   clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
 
  return clonedParms;
 }
 
 /// <summary>
 /// 准备一个待执行的SqlCommand
 /// </summary>
 private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType commandType, string commandText, params SqlParameter[] paras)
 {
  try
  {
   if (conn.State != ConnectionState.Open)
   {
    conn.Close();
    conn.Open();
   }
   cmd.Connection = conn;
   if (commandText != null)
    cmd.CommandText = commandText;
   cmd.CommandType = commandType;  //这里设置执行的是T-Sql语句还是存储过程
 
   if (trans != null)
    cmd.Transaction = trans;
 
   if (paras != null && paras.Length > 0)
   {
    //cmd.Parameters.AddRange(paras);
    for (int i = 0; i < paras.Length; i++)
    {
     if (paras[i].Value == null || paras[i].Value.ToString() == "")
      paras[i].Value = DBNull.Value; //插入或修改时,如果有参数是空字符串,那么以NULL的形式插入数据库
     cmd.Parameters.Add(paras[i]);
    }
   }
  }
  catch (Exception ex)
  {
   throw new Exception(ex.Message);
  }
 }
 
 /// <summary>
 /// 通用分页存储过程,有条件查询,有排序字段,按照排序字段的降序排列
 /// </summary>
 /// <param name="PageSize">每页记录数</param>
 /// <param name="CurrentCount">当前记录数量(页码*每页记录数)</param>
 /// <param name="TableName">表名称</param>
 /// <param name="Where">查询条件,例:"ID>1000 AND Name like '%LiLinFeng%'" 排序条件,直接在后面加,例:" ORDER BY ID DESC,NAME ASC"</param>
 /// <param name="TotalCount">记录总数</param>
 /// <returns></returns>
 public static DataSet GetList(string connectionString, string Order, int PageSize, int CurrentCount, string TableName, string Where, out int TotalCount)
 {
  SqlParameter[] parmList =
   {
    new SqlParameter("@PageSize",PageSize),
    new SqlParameter("@CurrentCount",CurrentCount),
    new SqlParameter("@TableName",TableName),
    new SqlParameter("@Where",Where),
    new SqlParameter("@Order",Order),
    new SqlParameter("@TotalCount",SqlDbType.Int,4)
   };
  parmList[5].Direction = ParameterDirection.Output;
  DataSet ds = GetDataset(connectionString, CommandType.StoredProcedure, "sp_MvcPager", parmList);
  TotalCount = Convert.ToInt32(parmList[5].Value);
  return ds;
 }
}

10.日志文件记录

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
public class WriteLog
{
 /// <summary>
 ///
 /// </summary>
 /// <param name="fileName">文件名</param>
 /// <param name="ex"></param>
 public static void WriteErorrLog(string fileName, Exception ex)
 {
  if (ex == null) return; //ex = null 返回
  DateTime dt = DateTime.Now; // 设置日志时间
  string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 时:分:秒
  string logName = dt.ToString("yyyy-MM-dd"); //日志名称
  string logPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine("log", fileName)); //日志存放路径
  string log = Path.Combine(logPath, string.Format("{0}.log", logName)); //路径 + 名称
  try
  {
   FileInfo info = new FileInfo(log);
   if (info.Directory != null && !info.Directory.Exists)
   {
    info.Directory.Create();
   }
   using (StreamWriter write = new StreamWriter(log, true, Encoding.GetEncoding("utf-8")))
   {
    write.WriteLine(time);
    write.WriteLine(ex.Message);
    write.WriteLine("异常信息:" + ex);
    write.WriteLine("异常堆栈:" + ex.StackTrace);
    write.WriteLine("异常简述:" + ex.Message);
    write.WriteLine("\r\n----------------------------------\r\n");
    write.Flush();
    write.Close();
    write.Dispose();
   }
  }
  catch { }
 }
 
 /// <summary>
 ///
 /// </summary>
 /// <param name="fileName">文件名</param>
 /// <param name="message"></param>
 public static void WriteMessage(string fileName, string message)
 {
  //ex = null 返回
  DateTime dt = DateTime.Now; // 设置日志时间
  string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 时:分:秒
  string logName = dt.ToString("yyyy-MM-dd"); //日志名称
  string logPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine("log", fileName)); //日志存放路径
  string log = Path.Combine(logPath, string.Format("{0}.log", logName)); //路径 + 名称
  try
  {
   FileInfo info = new FileInfo(log);
   if (info.Directory != null && !info.Directory.Exists)
   {
    info.Directory.Create();
   }
   using (StreamWriter write = new StreamWriter(log, true, Encoding.GetEncoding("utf-8")))
   {
    write.WriteLine(time);
    write.WriteLine("信息:" + message);
    write.WriteLine("\r\n----------------------------------\r\n");
    write.Flush();
    write.Close();
    write.Dispose();
   }
  }
  catch { }
 }
 
 
 public static void WriteErorrLog(Exception ex, string message)
 {
  if (ex == null) return; //ex = null 返回
  DateTime dt = DateTime.Now; // 设置日志时间
  string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 时:分:秒
  string logName = dt.ToString("yyyy-MM-dd"); //日志名称
  string logPath = System.AppDomain.CurrentDomain.BaseDirectory; //日志存放路径
  string log = Path.Combine(Path.Combine(logPath, "log"), string.Format("{0}.log", logName)); //路径 + 名称
  try
  {
   FileInfo info = new FileInfo(log);
   if (info.Directory != null && !info.Directory.Exists)
   {
    info.Directory.Create();
   }
   using (StreamWriter write = new StreamWriter(log, true, Encoding.GetEncoding("utf-8")))
   {
    write.WriteLine(time);
    write.WriteLine(ex.Message);
    write.WriteLine("异常信息:" + ex);
    write.WriteLine("异常堆栈:" + ex.StackTrace);
    write.WriteLine("异常简述:" + message);
    write.WriteLine("\r\n----------------------------------\r\n");
    write.Flush();
    write.Close();
    write.Dispose();
   }
  }
  catch { }
 }
 
 public static void WriteMessage(string message)
 {
  //ex = null 返回
  DateTime dt = DateTime.Now; // 设置日志时间
  string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 时:分:秒
  string logName = dt.ToString("yyyy-MM-dd"); //日志名称
  string logPath = System.AppDomain.CurrentDomain.BaseDirectory; //日志存放路径
  string log = Path.Combine(Path.Combine(logPath, "log"), string.Format("{0}.log", logName)); //路径 + 名称
  try
  {
   FileInfo info = new FileInfo(log);
   if (info.Directory != null && !info.Directory.Exists)
   {
    info.Directory.Create();
   }
   using (StreamWriter write = new StreamWriter(log, true, Encoding.GetEncoding("utf-8")))
   {
    write.WriteLine(time);
    write.WriteLine("信息:" + message);
    write.WriteLine("\r\n----------------------------------\r\n");
    write.Flush();
    write.Close();
    write.Dispose();
   }
  }
  catch { }
 }
}

11.JSON帮助类

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
/// <summary>
 /// JSON帮助类
 /// </summary>
 public class JsonHelper
 {
  #region 通用方法
  /// <summary>
  /// 格式化字符型、日期型、布尔型
  /// </summary>
  public static string StringFormat(string str, Type type)
  {
   if (type == typeof(string))
   {
    str = StringFilter(str);
    str = "\"" + str + "\"";
   }
   else if (type == typeof(DateTime) || type == typeof(DateTime?))
   {
    str = "\"" + str + "\"";
   }
   else if (type == typeof(bool))
   {
    str = str.ToLower();
   }
   else if (type == typeof(Guid))
   {
    str = "\"" + str + "\"";
   }
   else if (type != typeof(string) && string.IsNullOrEmpty(str))
   {
    str = "\"" + str + "\"";
   }
   return str;
  }
 
  /// <summary>
  /// 过滤字符串
  /// </summary>
  public static string StringFilter(string str)
  {
   StringBuilder sb = new StringBuilder();
   for (int i = 0; i < str.Length; i++)
   {
    char c = str.ToCharArray()[i];
    switch (c)
    {
     case '\"':
      sb.Append("\\\""); break;
     case '\\':
      sb.Append("\\\\"); break;
     case '/':
      sb.Append("\\/"); break;
     case '\b':
      sb.Append("\\b"); break;
     case '\f':
      sb.Append("\\f"); break;
     case '\n':
      sb.Append("\\n"); break;
     case '\r':
      sb.Append("\\r"); break;
     case '\t':
      sb.Append("\\t"); break;
     default:
      sb.Append(c); break;
    }
   }
   return sb.ToString();
  }
  #endregion
 
  #region 列转json
  /// <summary>
  /// 列转json
  /// </summary>
  /// <param name="dt">表</param>
  /// <param name="r">列</param>
  public static string ColumnToJson(DataTable dt, int r)
  {
   StringBuilder strSql = new StringBuilder();
   for (int i = 0; i < dt.Rows.Count; i++)
   {
    strSql.Append(dt.Rows[i][r]);
    strSql.Append(",");
   }
   return strSql.ToString().Trim(',');
  }
  #endregion
 
  #region 对象转json
  /// <summary>
  /// 对象转json
  /// </summary>
  public static string ToJson(object jsonObject)
  {
   StringBuilder sb = new StringBuilder();
   sb.Append("{");
   PropertyInfo[] propertyInfo = jsonObject.GetType().GetProperties();
   for (int i = 0; i < propertyInfo.Length; i++)
   {
    object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
    Type type = propertyInfo[i].PropertyType;
    string strValue = objectValue.ToString();
    strValue = StringFormat(strValue, type);
    sb.Append("\"" + propertyInfo[i].Name + "\":");
    sb.Append(strValue + ",");
   }
   sb.Remove(sb.Length - 1, 1);
   sb.Append("}");
   return sb.ToString();
  }
  #endregion
 
  #region list转json
  /// <summary>
  /// list转json
  /// </summary>
  public static string ListToJson<T>(IList<T> list)
  {
   object obj = list[0];
   return ListToJson<T>(list, obj.GetType().Name);
  }
 
  private static string ListToJson<T>(IList<T> list, string JsonName)
  {
   StringBuilder Json = new StringBuilder();
   if (string.IsNullOrEmpty(JsonName))
    JsonName = list[0].GetType().Name;
   Json.Append("{\"" + JsonName + "\":[");
   if (list.Count > 0)
   {
    for (int i = 0; i < list.Count; i++)
    {
     T obj = Activator.CreateInstance<T>();
     PropertyInfo[] pi = obj.GetType().GetProperties();
     Json.Append("{");
     for (int j = 0; j < pi.Length; j++)
     {
      Type type = pi[j].GetValue(list[i], null).GetType();
      Json.Append("\"" + pi[j].Name.ToString() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
      if (j < pi.Length - 1)
      {
       Json.Append(",");
      }
     }
     Json.Append("}");
     if (i < list.Count - 1)
     {
      Json.Append(",");
     }
    }
   }
   Json.Append("]}");
   return Json.ToString();
  }
  #endregion
 
  #region 对象集合转换为json
  /// <summary>
  /// 对象集合转换为json
  /// </summary>
  /// <param name="array">对象集合</param>
  /// <returns>json字符串</returns>
  public static string ToJson(IEnumerable array)
  {
   string jsonString = "[";
   foreach (object item in array)
   {
    jsonString += ToJson(item) + ",";
   }
   jsonString = jsonString.Substring(0, jsonString.Length - 1);
   return jsonString + "]";
  }
  #endregion
 
  #region 普通集合转换Json
  /// <summary>
  /// 普通集合转换Json
  /// </summary>
  /// <param name="array">集合对象</param>
  /// <returns>Json字符串</returns>
  public static string ToArrayString(IEnumerable array)
  {
   string jsonString = "[";
   foreach (object item in array)
   {
    jsonString = ToJson(item.ToString()) + ",";
   }
   jsonString.Remove(jsonString.Length - 1, jsonString.Length);
   return jsonString + "]";
  }
  #endregion
 
  #region DataSet转换为Json
  /// <summary>
  /// DataSet转换为Json
  /// </summary>
  /// <param name="dataSet">DataSet对象</param>
  /// <returns>Json字符串</returns>
  public static string ToJson(DataSet dataSet)
  {
   string jsonString = "{";
   foreach (DataTable table in dataSet.Tables)
   {
    jsonString += "\"" + table.TableName + "\":" + ToJson(table) + ",";
   }
   jsonString = jsonString.TrimEnd(',');
   return jsonString + "}";
  }
  #endregion
 
  #region Datatable转换为Json
  /// <summary> 
  /// Datatable转换为Json 
  /// </summary>
  public static string ToJson(DataTable dt)
  {
   if (dt.Rows.Count > 0)
   {
    StringBuilder jsonString = new StringBuilder();
    jsonString.Append("[");
    DataRowCollection drc = dt.Rows;
    for (int i = 0; i < drc.Count; i++)
    {
     jsonString.Append("{");
     for (int j = 0; j < dt.Columns.Count; j++)
     {
      string strKey = dt.Columns[j].ColumnName;
      string strValue = drc[i][j].ToString();
 
      Type type = dt.Columns[j].DataType;
      jsonString.Append("\"" + strKey + "\":");
      strValue = StringFormat(strValue, type);
      if (j < dt.Columns.Count - 1)
       jsonString.Append(strValue + ",");
      else
       jsonString.Append(strValue);
     }
     jsonString.Append("},");
    }
    jsonString.Remove(jsonString.Length - 1, 1);
    jsonString.Append("]");
    return jsonString.ToString();
   }
   else
    return "[]";
  }
 
  /// <summary>
  /// DataTable转换为Json
  /// </summary>
  public static string ToJson(DataTable dt, string jsonName)
  {
   StringBuilder Json = new StringBuilder();
   if (string.IsNullOrEmpty(jsonName))
    jsonName = dt.TableName;
   Json.Append("{\"" + jsonName + "\":[");
   if (dt.Rows.Count > 0)
   {
    for (int i = 0; i < dt.Rows.Count; i++)
    {
     Json.Append("{");
     for (int j = 0; j < dt.Columns.Count; j++)
     {
      Type type = dt.Rows[i][j].GetType();
      Json.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + StringFormat(dt.Rows[i][j].ToString(), type));
      if (j < dt.Columns.Count - 1)
       Json.Append(",");
     }
     Json.Append("}");
     if (i < dt.Rows.Count - 1)
      Json.Append(",");
    }
   }
   Json.Append("]}");
   return Json.ToString();
  }
  #endregion
 
  #region DataReader转换为Json
  /// <summary> 
  /// DataReader转换为Json 
  /// </summary> 
  /// <param name="dataReader">DataReader对象</param> 
  /// <returns>Json字符串</returns>
  public static string ToJson(DbDataReader dataReader)
  {
   StringBuilder jsonString = new StringBuilder();
   jsonString.Append("[");
   while (dataReader.Read())
   {
    jsonString.Append("{");
    for (int i = 0; i < dataReader.FieldCount; i++)
    {
     Type type = dataReader.GetFieldType(i);
     string strKey = dataReader.GetName(i);
     string strValue = dataReader[i].ToString();
     jsonString.Append("\"" + strKey + "\":");
     strValue = StringFormat(strValue, type);
     if (i < dataReader.FieldCount - 1)
      jsonString.Append(strValue + ",");
     else
      jsonString.Append(strValue);
    }
    jsonString.Append("},");
   }
   dataReader.Close();
   jsonString.Remove(jsonString.Length - 1, 1);
   jsonString.Append("]");
   return jsonString.ToString();
  }
  #endregion
 
 
  #region 返回错误
  public static string error()
  {
   DataTable dt = new DataTable();
   dt.Columns.Add("error", typeof(int));
   DataRow dr = dt.NewRow();
   dr["error"] = 1;
   dt.Rows.Add(dr);
   return ToJson(dt);
  }
  #endregion
 
 }
 
 
11.转换帮助类
 
 
 
 public class ConvertHelper
 {
  public static int DateTimeToUnixInt(DateTime time)
  {
   DateTime time2 = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(0x7b2, 1, 1));
   TimeSpan span = (TimeSpan)(time - time2);
   return (int)span.TotalSeconds;
  }
 
  public static decimal MoneyRound(decimal value, int decimals)
  {
   if (value < 0M)
   {
    return Math.Round((decimal)(value + (5M / ((decimal)Math.Pow(10.0, (double)(decimals + 1))))), decimals, MidpointRounding.AwayFromZero);
   }
   return Math.Round(value, decimals, MidpointRounding.AwayFromZero);
  }
 
  public static double MoneyRound(double value, int decimals)
  {
   if (value < 0.0)
   {
    return Math.Round((double)(value + (5.0 / Math.Pow(10.0, (double)(decimals + 1)))), decimals, MidpointRounding.AwayFromZero);
   }
   return Math.Round(value, decimals, MidpointRounding.AwayFromZero);
  }
 
  public static decimal MoneyToDecimal(string str)
  {
   try
   {
    str = str.Replace(",", "");
    return decimal.Parse(str);
   }
   catch
   {
    return 0M;
   }
  }
 
  public static decimal Round(decimal d, int i)
  {
   if (d >= 0M)
   {
    d += 5M * ((decimal)Math.Pow(10.0, (double)-(i + 1)));
   }
   else
   {
    d += -5M * ((decimal)Math.Pow(10.0, (double)-(i + 1)));
   }
   string str = d.ToString();
   string[] strArray = str.Split(new char[] { '.' });
   int index = str.IndexOf('.');
   string str2 = strArray[0];
   string str3 = strArray[1];
   if (str3.Length > i)
   {
    str3 = str.Substring(index + 1, i);
   }
   d = decimal.Parse(str2 + "." + str3);
   return d;
  }
 
  public static double Round(double d, int i)
  {
   if (d >= 0.0)
   {
    d += 5.0 * Math.Pow(10.0, (double)-(i + 1));
   }
   else
   {
    d += -5.0 * Math.Pow(10.0, (double)-(i + 1));
   }
   string str = d.ToString();
   string[] strArray = str.Split(new char[] { '.' });
   int index = str.IndexOf('.');
   string str2 = strArray[0];
   string str3 = strArray[1];
   if (str3.Length > i)
   {
    str3 = str.Substring(index + 1, i);
   }
   d = double.Parse(str2 + "." + str3);
   return d;
  }
 
  public static bool ToBool(object o)
  {
   return ToBool(o, false);
  }
 
  public static bool ToBool(object o, bool DefaultValue)
  {
   bool flag;
   if (bool.TryParse(ToString(o, true), out flag))
   {
    return flag;
   }
   return DefaultValue;
  }
 
  public static DateTime ToDateTime(object o)
  {
   return ToDateTime(o, DateTime.Now);
  }
 
  public static DateTime ToDateTime(object o, DateTime DefaultValue)
  {
   DateTime time;
   if (DateTime.TryParse(ToString(o, true), out time))
   {
    return time;
   }
   return DefaultValue;
  }
 
  public static decimal ToDecimal(object o)
  {
   return ToDecimal(o, 0M);
  }
 
  public static decimal ToDecimal(object o, decimal DefaultValue)
  {
   decimal num;
   if (decimal.TryParse(ToString(o, true), out num))
   {
    return num;
   }
   return DefaultValue;
  }
 
  public static double ToDouble(object o)
  {
   return ToDouble(o, 0.0);
  }
 
  public static double ToDouble(object o, double DefaultValue)
  {
   double num;
   if (double.TryParse(ToString(o, true), out num))
   {
    return num;
   }
   return DefaultValue;
  }
 
  public static float ToFloat(object o)
  {
   return ToFloat(o, 0f);
  }
 
  public static float ToFloat(object o, float DefaultValue)
  {
   float num;
   if (float.TryParse(ToString(o, true), out num))
   {
    return num;
   }
   return DefaultValue;
  }
 
  public static int ToInt(object o)
  {
   return ToInt(o, 0);
  }
 
  public static int ToInt(object o, int DefaultValue)
  {
   int num;
   if (int.TryParse(ToString(o, true), out num))
   {
    return num;
   }
   return DefaultValue;
  }
 
  public static long ToLong(object o)
  {
   return ToLong(o, 0L);
  }
 
  public static long ToLong(object o, long DefaultValue)
  {
   long num;
   if (long.TryParse(ToString(o, true), out num))
   {
    return num;
   }
   return DefaultValue;
  }
 
  public static string ToMoney(object o)
  {
   return ToDecimal(o).ToString("###,###,###,###,###,##0.##");
  }
 
  public static string ToMoney(string str)
  {
   try
   {
    return decimal.Parse(str).ToString("###,###,###,###,###,##0.##");
   }
   catch
   {
    return "0";
   }
  }
 
  public static string ToString(object o)
  {
   return ToString(o, "", false);
  }
 
  public static string ToString(object o, bool bTrim)
  {
   return ToString(o, "", bTrim);
  }
 
  public static string ToString(object o, string DefaultValue)
  {
   return ToString(o, DefaultValue, false);
  }
 
  public static string ToString(object o, string DefaultValue, bool bTrim)
  {
   if (object.Equals(o, null) || Convert.IsDBNull(o))
   {
    return DefaultValue;
   }
   if (bTrim)
   {
    return o.ToString().Trim();
   }
   return o.ToString();
  }
 
  public static DateTime UnixIntToDateTime(string timeStamp)
  {
   DateTime time = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(0x7b2, 1, 1));
   long ticks = long.Parse(timeStamp + "0000000");
   TimeSpan span = new TimeSpan(ticks);
   return time.Add(span);
  }
 }

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

延伸 · 阅读

精彩推荐
  • C#如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    这篇文章主要给大家介绍了关于如何使用C#将Tensorflow训练的.pb文件用在生产环境的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴...

    bbird201811792022-03-05
  • C#利用C#实现网络爬虫

    利用C#实现网络爬虫

    这篇文章主要介绍了利用C#实现网络爬虫,完整的介绍了C#实现网络爬虫详细过程,感兴趣的小伙伴们可以参考一下...

    C#教程网11852021-11-16
  • C#三十分钟快速掌握C# 6.0知识点

    三十分钟快速掌握C# 6.0知识点

    这篇文章主要介绍了C# 6.0的相关知识点,文中介绍的非常详细,通过这篇文字可以让大家在三十分钟内快速的掌握C# 6.0,需要的朋友可以参考借鉴,下面来...

    雨夜潇湘8272021-12-28
  • C#C#微信公众号与订阅号接口开发示例代码

    C#微信公众号与订阅号接口开发示例代码

    这篇文章主要介绍了C#微信公众号与订阅号接口开发示例代码,结合实例形式简单分析了C#针对微信接口的调用与处理技巧,需要的朋友可以参考下...

    smartsmile20127762021-11-25
  • C#VS2012 程序打包部署图文详解

    VS2012 程序打包部署图文详解

    VS2012虽然没有集成打包工具,但它为我们提供了下载的端口,需要我们手动安装一个插件InstallShield。网上有很多第三方的打包工具,但为什么偏要使用微软...

    张信秀7712021-12-15
  • C#SQLite在C#中的安装与操作技巧

    SQLite在C#中的安装与操作技巧

    SQLite,是一款轻型的数据库,用于本地的数据储存。其优点有很多,下面通过本文给大家介绍SQLite在C#中的安装与操作技巧,感兴趣的的朋友参考下吧...

    蓝曈魅11162022-01-20
  • C#C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    这篇文章主要介绍了C#设计模式之Strategy策略模式解决007大破密码危机问题,简单描述了策略模式的定义并结合加密解密算法实例分析了C#策略模式的具体使用...

    GhostRider10972022-01-21
  • C#深入理解C#的数组

    深入理解C#的数组

    本篇文章主要介绍了C#的数组,数组是一种数据结构,详细的介绍了数组的声明和访问等,有兴趣的可以了解一下。...

    佳园9492021-12-10