首页 > 代码库 > C#生成字母和数字组成的随机文件
C#生成字母和数字组成的随机文件
代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using System.Collections; using System.IO; namespace FileGenerator { class Program { static void Main(string[] args) { Program program = new Program(); //IDictionary<string, string> dictionary = (IDictionary<string, string>)ConfigurationSettings.GetConfig("App.config"); string path = ConfigurationManager.AppSettings["path"]; int miniSize = int.Parse(ConfigurationManager.AppSettings["miniSize"]); int maxSize = int.Parse(ConfigurationManager.AppSettings["maxSize"]); long quantity = long.Parse(ConfigurationManager.AppSettings["quantity"]); string prefix = ConfigurationManager.AppSettings["prefix"]; //Console.WriteLine(path); //Console.ReadLine(); DirectoryInfo directory = new DirectoryInfo(path); if (!directory.Exists) { Directory.CreateDirectory(path); } int j = 0; while (j < quantity) { j++; string fileName = path + prefix + "_"; Random random = new Random(); for (int i = 1; i <= 10; i++) { fileName = fileName + random.Next(10); } FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("gb2312")); try { string content = program.GetFileContent(miniSize, maxSize); sw.Flush(); sw.BaseStream.Seek(0, SeekOrigin.Begin); sw.WriteLine(content); sw.Flush(); sw.Close(); //char[] contentChar = content.ToCharArray(); //Encoder encoder = Encoding.UTF8.GetEncoder(); //byte[] bytes = new byte[4096]; //encoder.GetBytes(contentChar, 0, contentChar.Length, bytes, 0, true); //fs.Seek(0, SeekOrigin.Begin); //fs.Write(bytes, 0, bytes.Length); //fs.Close(); } catch (IOException) { continue; sw.Close(); } } } public string GetFileContent(int miniSize, int maxSize) { List<string> strList = new List<string>(); for (int i = 65; i < 90; i++) { char aa = (char)i; strList.Add(aa.ToString()); } for (int i = 97; i < 122; i++) { char aa = (char)i; strList.Add(aa.ToString()); } char[] number = new char[10]; for (int i = 48; i <= 57; i++) { char aa = (char)i; strList.Add(aa.ToString()); number[i - 48] = aa; } string content = ""; double size = (miniSize + (maxSize - miniSize) * new Random().NextDouble())*1024; for (int i = 0; i < size; i++) { Random random = new Random(); int index = random.Next(strList.Count-1); content = content + strList[index]; //content = content + strList[strList.Count]; } return content; } } }
配置文件App.config信息:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="path" value="D:\SourceFolder\sftptest\"/> <add key="miniSize" value="20"/> <add key="maxSize" value="40"/> <add key="quantity" value="10"/> <add key ="prefix" value="test"/> </appSettings> </configuration>
注意两点:
1.App.Config的格式要严格按照上面这个格式来写
2.build之后,App.config名字会变成程序名称加config,exe和config要在一个目录下
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。