RamdomCode()方法生成8位随机码 保存到F盘符下user.txt initUser()读取user.txt,序列化后保存到F盘符下User.dat using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Runtime.Serialization.Formatters.Binary; using System.IO; using CreateCode; namespace ConsoleApplication1 { class Program { private static void initUser() { List<LoginUser> users = new List<LoginUser>(); StreamReader reader = new StreamReader("F:/User.txt"); string temp = string.Empty; while ((temp = reader.ReadLine()) != null) { users.Add(new LoginUser(temp.Split(',')[0], Convert.ToInt32(temp.Split(',')[1]))); } BinaryFormatter bf = new BinaryFormatter(); FileStream fs = new FileStream("f:/User.dat", FileMode.Create); bf.Serialize(fs, users); fs.Close(); } public static void RamdomCode() { StreamWriter file = new StreamWriter(new FileStream("f:/User.txt", FileMode.Create)); List<string> strlist = new List<string>(); char[] Pattern = new char[] { '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; string result = ""; int n = Pattern.Length; Random random = new Random(~unchecked((int)DateTime.Now.Ticks)); for (int i = 0; i < 100; ) { for (int j = 0; j < 8; j++) { int rnd = random.Next(0, n); Thread.Sleep(10); result += Pattern[rnd]; } if (strlist.Contains(result)) { continue; } else { Console.WriteLine(result); strlist.Add(result); file.WriteLine(result + ",0"); result = ""; i++; } } file.Close(); } static void Main(string[] args) { RamdomCode(); initUser(); } } } 反序列化保存到List BinaryFormatter bf = new BinaryFormatter(); FileStream ff = new FileStream("F:/User.dat", FileMode.Open); List<LoginUser> users = bf.Deserialize(ff) as List<LoginUser>; ff.Close();