如何生成在C#中一个随机命名的文本文件? [英] How to generate a random named text file in C#?

查看:329
本文介绍了如何生成在C#中一个随机命名的文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须作出一个循环来生成一个随机5采摘字母串,然后再根据该名称创建一个文本文件,可以用C说://,我将如何做呢?同时产生的名称和创建的目录中的文件。我想我要挑5的随机数从ASCII代码将它们添加到一个数组,然后将它们转换为字符等效,以便能够使用它作为一个名称。 IDK我将如何把它们转换成字符,并与他们的字符串,你能帮我吗?


解决方案

如果你想创建文件名youself,把你想在一个字符串使用,并从挑选字符:

  //选择字符
串字符=2346789ABCDEFGHJKLMNPQRTUVWXYZabcdefghjkmnpqrtuvwxyz;
//创建随机数发生器
随机RND =新的随机();
字符串名称;
做{
//创建名
NAME =的String.Empty;
,而(name.Length小于5){
名称+ = chars.Substring(rnd.Next(chars.Length),1);
}
//添加扩展
名称+ =.TXT;
//核对在该文件夹
},而(File.Exists(Path.Compbine(FOLDERPATH,名)))

I have to make a loop to generate a 5 randomly-picked-letter string, and then create a text file under that name, lets say in C:// , how will I do that? Both the generating name and creating a file in the directory. I think I have to pick 5 random numbers from the ascii codes add them to an array and then convert them to the character equivalents to be able to use it as a name. Idk how I'll convert them to character and make up a string with them, could you help me?

解决方案

If you want to create the file names youself, put the characters that you want to use in a string and pick from that:

// selected characters
string chars = "2346789ABCDEFGHJKLMNPQRTUVWXYZabcdefghjkmnpqrtuvwxyz";
// create random generator
Random rnd = new Random();
string name;
do {
   // create name
   name = string.Empty;
   while (name.Length < 5) {
      name += chars.Substring(rnd.Next(chars.Length), 1);
   }
   // add extension
   name += ".txt";
   // check against files in the folder
} while (File.Exists(Path.Compbine(folderPath, name)))

这篇关于如何生成在C#中一个随机命名的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆