一. IO读写
这里主要包括文件的读、写、移动、复制、删除、文件夹的创建、文件夹的删除等常规操作。
注意:这里需要特别注意,对于普通的控制台程序和Web程序,将"相对路径"转换成"绝对路径"的方法不一致。
(1). 在web程序中,可以使用HttpContext.Current.Server.MapPath进行转换,使用方法通过 ~/定位到一级目录,eg:FileOperateHelp.Write_Txt("~/TestFile/mr.txt", "mr")。
(2). 在普通的控制台程序中,HttpContext.Current为空,所以web中的转换方式在控制台中失效,需要借助 "AppDomain.CurrentDomain.BaseDirectory"来获取根目录,该目录直接定位到Debug文件夹,然后利用System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath)传入路径与根目录进行结合,所以普通的控制台程序生成的所有文件均在Debug文件夹下,当然,你也可以直接写绝对路径,比如D:xxx。
下面的方法就是专门处理普通程序和web程序路径转换问题的。
1 /// <summary>2 /// 10.将相对路径转换成绝对路径3 /// </summary>4 /// <param name="strPath">相对路径</param>5 public static string PathConvert(string strPath)6 {7 //web程序使用8 if (HttpContext.Current != null)9 {
10 return HttpContext.Current.Server.MapPath(strPath);
11 }
12 else //非web程序引用
13 {
14 strPath = strPath.Replace("/", "\\");
15 if (strPath.StartsWith("\\"))
16 {
17 strPath = strPath.TrimStart('\\');
18 }
19 return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
20 }
21 }
下面分享一个FileOperateHelp类,里面包含IO的常规操作。
View Code
1. 在控制台中进行调用。
1 //1.写文件测试(覆盖写入)2 FileOperateHelp.Write_Txt("TestFile/mr.txt", "mr123");3 FileOperateHelp.Write_Txt("TestFile/mr2.txt", "mr123");4 //2.读文件测试5 string msg1 = FileOperateHelp.Read_Txt("TestFile/mr.txt");6 7 //3.写文件测试(追加写入)8 FileOperateHelp.WriteFile("TestFile/mr.txt", "123456");9 //4.读文件测试
10 string msg2 = FileOperateHelp.ReadFile("TestFile/mr.txt");
11
12 //5.删除文件测试
13 FileOperateHelp.FileDel("TestFile/mr2.txt");
14
15 //6.移动文件测试
16 FileOperateHelp.FileMove("TestFile/mr.txt", "TestFile/TEST/mr移动.txt");
17
18 //7.复制文件测试
19 FileOperateHelp.FileCopy("TestFile/mr3.txt", "TestFile/TEST/mr3Copy.txt");
20
21 //8.创建文件夹
22 FileOperateHelp.FolderCreate("TestFile/TEST2");
23
24 //9.递归删除文件夹(删除a文件夹)
25 FileOperateHelp.DeleteFolder("TestFile/TestDel/a/");
2. 在Web程序中进行调用
1 public void Index()2 {3 //1.写文件测试(覆盖写入)4 FileOperateHelp.Write_Txt("~/TestFile/mr.txt", "mr123");5 FileOperateHelp.Write_Txt("~/TestFile/mr2.txt", "mr123");6 //2.读文件测试7 string msg1 = FileOperateHelp.Read_Txt("~/TestFile/mr.txt");8 9 //3.写文件测试(追加写入)
10 FileOperateHelp.WriteFile("~/TestFile/mr.txt", "123456");
11 //4.读文件测试
12 string msg2 = FileOperateHelp.ReadFile("~/TestFile/mr.txt");
13
14 //5.删除文件测试
15 FileOperateHelp.FileDel("~/TestFile/mr2.txt");
16
17 //6.移动文件测试
18 FileOperateHelp.FileMove("~/TestFile/mr.txt", "~/TestFile/TEST/mr移动.txt");
19
20 //7.复制文件测试
21 FileOperateHelp.FileCopy("~/TestFile/mr3.txt", "~/TestFile/TEST/mr3Copy.txt");
22
23 //8.创建文件夹
24 FileOperateHelp.FolderCreate("~/TestFile/TEST2");
25
26 //9.递归删除文件夹(删除a文件夹)
27 FileOperateHelp.DeleteFolder("~/TestFile/TestDel/a/");
28
29 }
二. 序列化和反序列化
1. 在.Net中,序列化和反序列化主要有两种 :
方案一:利用JavaScriptSerializer对象实现,需要添加System.Web.Extensions程序集的引用。
方案二:利用程序集Newtonsoft.Json.dll来实现。
注意:如果要把某个类序列化,需要在该类上面加一个 [Serializable]属性。
下面分享一个JsonHelp类,该类主要提供两种序列化和反序列化的方法,代码如下:
1 public class JsonHelp2 {3 #region 01-将JSON转换成JSON字符串4 /// <summary>5 /// 将JSON转换成JSON字符串6 /// </summary>7 /// <typeparam name="T"></typeparam>8 /// <param name="obj"></param>9 /// <returns></returns>
10 public static string ObjectToString<T>(T obj)
11 {
12 JavaScriptSerializer jss = new JavaScriptSerializer();
13 return jss.Serialize(obj);
14 }
15 #endregion
16
17 #region 02-将字符串转换成JSON对象
18 /// <summary>
19 /// 将字符串转换成JSON对象
20 /// </summary>
21 /// <typeparam name="T"></typeparam>
22 /// <param name="content"></param>
23 /// <returns></returns>
24 public static T StringToObject<T>(string content)
25 {
26 JavaScriptSerializer jss = new JavaScriptSerializer();
27 return jss.Deserialize<T>(content);
28 }
29 #endregion
30
31 #region 03-将JSON转换成JSON字符串
32 /// <summary>
33 ///将JSON转换成JSON字符串
34 /// </summary>
35 /// <typeparam name="T"></typeparam>
36 /// <param name="obj"></param>
37 /// <returns></returns>
38 public static string ToJsonString<T>(T obj)
39 {
40 return JsonConvert.SerializeObject(obj);
41 }
42 #endregion
43
44 #region 04-将字符串转换成JSON对象
45 /// <summary>
46 /// 将字符串转换成JSON对象
47 /// </summary>
48 /// <typeparam name="T"></typeparam>
49 /// <param name="content"></param>
50 /// <returns></returns>
51 public static T ToObject<T>(string content)
52 {
53 return JsonConvert.DeserializeObject<T>(content);
54 }
55 #endregion
56 }
2. 代码调用:
1 //1. 将JSON对象转换成JSON字符串2 Console.WriteLine("-------------------------------------1. 将JSON转换成JSON字符串------------------------------------------");3 var myObj = new4 {5 id = "1",6 name = "ypf",7 myList = studentList,8 myList2 = studentList.Where(u => u.Age > 27).Select(u => new9 {
10 t1 = u.Age,
11 t2 = u.ClassId
12 }).ToList()
13
14 };
15 //1.1 方式一
16 string myString1 = JsonHelp.ObjectToString(myObj);
17 //1.2 方式二
18 string myString2 = JsonHelp.ToJsonString(myObj);
19 string myString3 = JsonHelp.ToJsonString(studentList);
20 Console.WriteLine(myString1);
21 Console.WriteLine(myString2);
22 //2. 将JSON字符串转换成JSON对象(必须显式的声明对象)
23 List<Student> myList = JsonHelp.StringToObject<List<Student>>(myString3);
24 Console.WriteLine(myList);
三. 加密和解密
这里介绍三种加密方式,分别是:
(1). MD5不可逆加密:加密后可以是16位,也可以是32位,任何语言的MD5加密后的结果都相同。
(2). DES可逆对称加密:
优点:对称加密算法的优点是速度快。
缺点:密钥管理不方便,要求共享密钥。
特点:不同写法对应的加密值不同。
(3). RSA可逆非对称加密:
特点:可逆非对称加密,需要两个Key,公钥和私钥,每次产生的公钥和私钥不一致,加密的结果就不一致
好处:非对称加密算法的优点是密钥管理很方便,缺点是速度慢。
特性(重点!!!):需要通过代码来生成一对公钥(加密key)和私钥(解密key),公钥私钥只与是否公开有关。
A. 如果公开公钥(加密key):只有我接受加密信息才有用,因为只有我有私钥(解密key),能解密。
B. 如果公开私钥(解密key):用于签名,表示加密数据一定是我发的,因为只有公钥(加密key)。
1. 下面分享两种MD5实现的算法
/// <summary>/// MD5加密,和动网上的16/32位MD5加密结果相同,/// 使用的UTF8编码/// </summary>/// <param name="strSource">待加密字串</param>/// <param name="length">16或32值之一,其它则采用.net默认MD5加密算法</param>/// <returns>加密后的字串</returns>public static string Encrypt(string source, int length = 32)//默认参数{HashAlgorithm provider = CryptoConfig.CreateFromName("MD5") as HashAlgorithm;if (string.IsNullOrEmpty(source)) return string.Empty;byte[] bytes = Encoding.UTF8.GetBytes(source);// Encoding.ASCII.GetBytes(source);byte[] hashValue = provider.ComputeHash(bytes);StringBuilder sb = new StringBuilder();switch (length){case 16://16位密文是32位密文的9到24位字符for (int i = 4; i < 12; i++)sb.Append(hashValue[i].ToString("x2"));break;case 32:for (int i = 0; i < 16; i++){sb.Append(hashValue[i].ToString("x2"));}break;default:for (int i = 0; i < hashValue.Length; i++){sb.Append(hashValue[i].ToString("x2"));}break;}return sb.ToString();} /// <summary>/// MD5加密/// </summary>/// <param name="str">要加密的字符串</param>/// <returns>加密后的字符串</returns>public static string Md5(string str){var md5 = MD5.Create();// 计算字符串的散列值var bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(str));var sbd = new StringBuilder();foreach (var item in bytes){sbd.Append(item.ToString("x2"));}return sbd.ToString();}
2. 下面分享两种DES实现的算法
1 public class DesEncrypt2 {3 //8位长度4 private static string KEY = "ypf12345";5 private static byte[] rgbKey = ASCIIEncoding.ASCII.GetBytes(KEY.Substring(0, 8));6 private static byte[] rgbIV = ASCIIEncoding.ASCII.GetBytes(KEY.Insert(0, "w").Substring(0, 8));7 8 #region 01-DES加密9 /// <summary>
10 /// DES 加密
11 /// </summary>
12 /// <param name="strValue">需要加密的字符串</param>
13 /// <returns></returns>
14 public static string Encrypt(string strValue)
15 {
16 DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
17 using (MemoryStream memStream = new MemoryStream())
18 {
19 CryptoStream crypStream = new CryptoStream(memStream, dsp.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
20 StreamWriter sWriter = new StreamWriter(crypStream);
21 sWriter.Write(strValue);
22 sWriter.Flush();
23 crypStream.FlushFinalBlock();
24 memStream.Flush();
25 return Convert.ToBase64String(memStream.GetBuffer(), 0, (int)memStream.Length);
26 }
27 }
28 #endregion
29
30 #region 02-DES解密
31 /// <summary>
32 /// DES解密
33 /// </summary>
34 /// <param name="EncValue">加密后的结果</param>
35 /// <returns></returns>
36 public static string Decrypt(string EncValue)
37 {
38 DESCryptoServiceProvider dsp = new DESCryptoServiceProvider();
39 byte[] buffer = Convert.FromBase64String(EncValue);
40
41 using (MemoryStream memStream = new MemoryStream())
42 {
43 CryptoStream crypStream = new CryptoStream(memStream, dsp.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
44 crypStream.Write(buffer, 0, buffer.Length);
45 crypStream.FlushFinalBlock();
46 return ASCIIEncoding.UTF8.GetString(memStream.ToArray());
47 }
48 }
49 #endregion
50 }
1 #region 3.DES加密一个字符串(可逆,非固定)2 /// <summary>3 /// 加密一个字符串(可逆,非固定)4 /// </summary>5 /// <param name="str">要加密的字符串</param>6 /// <param name="key">加密密钥</param>7 /// <returns>加密后的字符串</returns>8 public static string EncryptStr(string str, string key = "iceStone")9 {
10 var des = DES.Create();
11 // var timestamp = DateTime.Now.ToString("HHmmssfff");
12 var inputBytes = Encoding.UTF8.GetBytes(MixUp(str));
13 var keyBytes = Encoding.UTF8.GetBytes(key);
14 SHA1 ha = new SHA1Managed();
15 var hb = ha.ComputeHash(keyBytes);
16 var sKey = new byte[8];
17 var sIv = new byte[8];
18 for (var i = 0; i < 8; i++)
19 sKey[i] = hb[i];
20 for (var i = 8; i < 16; i++)
21 sIv[i - 8] = hb[i];
22 des.Key = sKey;
23 des.IV = sIv;
24 using (var ms = new MemoryStream())
25 {
26 using (var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
27 {
28 cs.Write(inputBytes, 0, inputBytes.Length);
29 cs.FlushFinalBlock();
30 var ret = new StringBuilder();
31 foreach (var b in ms.ToArray())
32 {
33 ret.AppendFormat("{0:X2}", b);
34 }
35
36 return ret.ToString();
37 }
38 }
39 }
40 #endregion
41
42 #region 4.DES解密一个字符串
43 /// <summary>
44 /// 解密一个字符串
45 /// <param name="str">要解密的字符串</param>
46 /// <param name="key">加密密钥</param>
47 /// <returns>解密后的字符串</returns>
48 public static string DecryptStr(string str, string key = "iceStone")
49 {
50 var des = DES.Create();
51 var inputBytes = new byte[str.Length / 2];
52 for (var x = 0; x < str.Length / 2; x++)
53 {
54 inputBytes[x] = (byte)System.Convert.ToInt32(str.Substring(x * 2, 2), 16);
55 }
56 var keyByteArray = Encoding.UTF8.GetBytes(key);
57 var ha = new SHA1Managed();
58 var hb = ha.ComputeHash(keyByteArray);
59 var sKey = new byte[8];
60 var sIv = new byte[8];
61 for (var i = 0; i < 8; i++)
62 sKey[i] = hb[i];
63 for (var i = 8; i < 16; i++)
64 sIv[i - 8] = hb[i];
65 des.Key = sKey;
66 des.IV = sIv;
67 using (var ms = new MemoryStream())
68 {
69 using (var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
70 {
71 cs.Write(inputBytes, 0, inputBytes.Length);
72 cs.FlushFinalBlock();
73 return ClearUp(Encoding.UTF8.GetString(ms.ToArray()));
74 }
75 }
76 }
77 #endregion
3. 下面分享RSA的代码
1 public class RsaEncrypt2 {3 4 #region 01-生成公钥和私钥5 /// <summary>6 /// 生成公钥和私钥7 /// </summary>8 /// <returns></returns>9 public static KeyValuePair<string, string> GetKeyPair()
10 {
11 RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
12 string publicKey = RSA.ToXmlString(false);
13 string privateKey = RSA.ToXmlString(true);
14 return new KeyValuePair<string, string>(publicKey, privateKey);
15 }
16 #endregion
17
18 #region 02-加密(传入内容和公钥)
19 /// <summary>
20 /// 加密:内容+公钥,事先需要生成公钥和私钥
21 /// </summary>
22 /// <param name="content">加密内容</param>
23 /// <param name="publicKey">公钥</param>
24 /// <returns></returns>
25 public static string Encrypt(string content, string publicKey)
26 {
27 RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
28 rsa.FromXmlString(publicKey);
29 UnicodeEncoding ByteConverter = new UnicodeEncoding();
30 byte[] DataToEncrypt = ByteConverter.GetBytes(content);
31 byte[] resultBytes = rsa.Encrypt(DataToEncrypt, false);
32 return Convert.ToBase64String(resultBytes);
33 }
34 #endregion
35
36 #region 03-加密(并返回公钥和私钥)
37 /// <summary>
38 /// 加密(并返回公钥和私钥),在该方法中生成了公钥和私钥,并返回
39 /// </summary>
40 /// <param name="content">加密内容</param>
41 /// <param name="publicKey">返还公钥</param>
42 /// <param name="privateKey">返回密钥</param>
43 /// <returns>加密后结果</returns>
44 public static string Encrypt(string content, out string publicKey, out string privateKey)
45 {
46 RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
47 publicKey = rsaProvider.ToXmlString(false);
48 privateKey = rsaProvider.ToXmlString(true);
49 UnicodeEncoding ByteConverter = new UnicodeEncoding();
50 byte[] DataToEncrypt = ByteConverter.GetBytes(content);
51 byte[] resultBytes = rsaProvider.Encrypt(DataToEncrypt, false);
52 return Convert.ToBase64String(resultBytes);
53 }
54 #endregion
55
56 #region 04-解密(内容+私钥)
57 /// <summary>
58 /// 解密-内容+私钥
59 /// </summary>
60 /// <param name="content"></param>
61 /// <param name="privateKey"></param>
62 /// <returns></returns>
63 public static string Decrypt(string content, string privateKey)
64 {
65 byte[] dataToDecrypt = Convert.FromBase64String(content);
66 RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
67 RSA.FromXmlString(privateKey);
68 byte[] resultBytes = RSA.Decrypt(dataToDecrypt, false);
69 UnicodeEncoding ByteConverter = new UnicodeEncoding();
70 return ByteConverter.GetString(resultBytes);
71 }
72 #endregion
73 }
4. 分享加密算法的调用代码
1 {2 Console.WriteLine("-------------------------------------三.3种加密方式------------------------------------------");3 {4 Console.WriteLine("----------------------1.MD5加密(加密后结果可以是32位,也可以是16位,主流都采用32位)-----------------------------");5 //1.MD5加密(加密后结果可以是32位,也可以是16位,主流都采用32位)6 //1.1 写法一7 string msg1 = "mr1";8 string result1 = MD5Encrypt.Encrypt(msg1);9 string result2 = MD5Encrypt.Encrypt(msg1, 16);
10 Console.WriteLine(result1);
11 Console.WriteLine(result2);
12 //1.2 写法二 .Net 高度封装的MD5方法
13 string result3 = SecurityHelp.Md5(msg1);
14 Console.WriteLine(result3);
15 }
16 {
17 Console.WriteLine("----------------------2.对称可逆加密算法DES-----------------------------");
18 //2.对称加密算法DES
19 string msg1 = "mr1";
20 //2.1 写法一:密钥写在DesEncrypt类中了,密钥为ypf12345
21 string result1 = DesEncrypt.Encrypt(msg1);
22 string result2 = DesEncrypt.Decrypt(result1);
23 Console.WriteLine(result1);
24 Console.WriteLine(result2);
25 //2.2 写法二
26 string result3 = SecurityHelp.EncryptStr(msg1, "ypf12345");
27 string result4 = SecurityHelp.DecryptStr(result3, "ypf12345");
28 Console.WriteLine(result3);
29 Console.WriteLine(result4);
30 }
31 {
32 Console.WriteLine("----------------------3.非对称可逆加密算法RSA-----------------------------");
33 //方式一:先生成公钥和私钥,然后加密和解密
34 //KeyValuePair是一个键值对, myKey.Key 代表的公钥;myKey.Value 代表的私钥
35 KeyValuePair<string, string> myKey = RsaEncrypt.GetKeyPair();
36 string msg1 = "mr1";
37 //加密
38 string result1 = RsaEncrypt.Encrypt(msg1, myKey.Key);
39 //解密
40 string result2 = RsaEncrypt.Decrypt(result1, myKey.Value);
41 Console.WriteLine(result1);
42 Console.WriteLine(result2);
43 //方式二:直接加密,并通过out参数的形式返回公钥和私钥
44 string publicKey = "";
45 string privateKey = "";
46 //加密
47 string result3 = RsaEncrypt.Encrypt(msg1, out publicKey, out privateKey);
48 //解密
49 string result4 = RsaEncrypt.Decrypt(result3, privateKey);
50 Console.WriteLine(result3);
51 Console.WriteLine(result4);
52 }
53
54 }
运行结果: