如何在 C# 中生成随机命名的文本文件?
我必须创建一个循环来生成一个 5 个随机选择的字母字符串,然后在该名称下创建一个文本文件,比如说 C:// ,我将如何做到这一点? 生成名称并在目录中创建文件。 我想我必须从 ascii 代码中挑选 5 个随机数,将它们添加到一个数组中,然后将它们转换为等效字符才能将其用作名称。 我不知道如何将它们转换为字符并用它们组成一个字符串,你能帮我吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
或者您可以使用 GUID 来生成唯一的文件名:
维基百科:
Or you could use a GUID for generating a unique filename:
Wikipedia:
一段生成随机字符串(字母)的代码发布在 此处。 创建文件(也使用随机文件名)的代码位于此处 。
A piece of code that generates a random string (of letters) was posted here. Code that creates files (also using random file names) is available here.
此处):
在 Google 上为您找到了此内容(来源位于 即,使用文件流来创建和写入文件。
found this on Google for you (source here):
After that, use file streams to create and write the file.
查看 System.IO.Path< 的 GetTempFileName 和 GetRandomFileName 方法/a> 类。
GetRandomFileName 创建“加密强度高” " 文件名,与您要求的文件名最接近。
GetTempFileName 创建唯一的文件名在目录中 - 并且还创建一个具有该名称的零字节文件 - 有助于确保其唯一性。 这可能更接近您实际需要的内容。
Look at the GetTempFileName and GetRandomFileName methods of the System.IO.Path class.
GetRandomFileName creates a "cryptographically strong" file name, and is the closer one to what you asked for.
GetTempFileName creates a unique file name in a directory -- and also creates a zero-byte file with that name too -- helping ensure its uniqueness. This might be closer to what you might actually need.
如果您想自己创建文件名,请将要使用的字符放入字符串中并从中选择:
If you want to create the file names youself, put the characters that you want to use in a string and pick from that:
Path.GetTempFileName() 或 Path.GetRandomFileName() 方法怎么样? 还要考虑文件系统不是事务性的并且两个并行进程可以创建相同的文件名这一事实。 TempFileName() 应该返回唯一的名称(根据规范),因此“也许”您不需要关心临时目录是否适合您的解决方案。
What about Path.GetTempFileName() or Path.GetRandomFileName() methods? Consider also the fact that file system is not transactional and two parallel processes can create the same file name. TempFileName() should return unique name (by specification), so 'maybe' you don't need to care about that if the temp directory could be fine for your solution.