如何在 C# 中生成随机命名的文本文件?

发布于 2024-08-01 22:56:59 字数 183 浏览 3 评论 0原文

我必须创建一个循环来生成一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

巷雨优美回忆 2024-08-08 22:56:59

或者您可以使用 GUID 来生成唯一的文件名:

维基百科:

虽然每个生成的 GUID 不是
保证是唯一的,总数
唯一键的数量(2^128 或
3.4×10^38) 如此之大以至于相同数字的概率
生成两次是无限小的。

string text = "Sample...";
string path = "D:\\Temp\\";

if (!path.EndsWith("\\"))
    path += "\\";

string filename = path + Guid.NewGuid().ToString() + ".txt";
while (File.Exists(filename))
    filename = path + Guid.NewGuid().ToString() + ".txt";

TextWriter writer = null;
try
{
    writer = new StreamWriter(filename);
    writer.WriteLine(text);
    writer.Close();
}
catch (Exception e)
{
    MessageBox.Show("Exception occured: " + e.ToString());
}
finally
{
    if (writer != null)
        writer.Close();
}

Or you could use a GUID for generating a unique filename:

Wikipedia:

While each generated GUID is not
guaranteed to be unique, the total
number of unique keys (2^128 or
3.4×10^38) is so large that the probability of the same number being
generated twice is infinitesimally small.

string text = "Sample...";
string path = "D:\\Temp\\";

if (!path.EndsWith("\\"))
    path += "\\";

string filename = path + Guid.NewGuid().ToString() + ".txt";
while (File.Exists(filename))
    filename = path + Guid.NewGuid().ToString() + ".txt";

TextWriter writer = null;
try
{
    writer = new StreamWriter(filename);
    writer.WriteLine(text);
    writer.Close();
}
catch (Exception e)
{
    MessageBox.Show("Exception occured: " + e.ToString());
}
finally
{
    if (writer != null)
        writer.Close();
}
眼眸里的快感 2024-08-08 22:56:59

一段生成随机字符串(字母)的代码发布在 此处。 创建文件(也使用随机文件名)的代码位于此处

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.

つ低調成傷 2024-08-08 22:56:59

此处):

/// <summary>
/// Generates a random string with the given length
/// </summary>
/// <param name="size">Size of the string</param>
/// <param name="lowerCase">If true, generate lowercase string</param>
/// <returns>Random string</returns>
private string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch ;
for(int i=0; i<size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ;
builder.Append(ch); 
}
if(lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}

在 Google 上为您找到了此内容(来源位于 即,使用文件流来创建和写入文件。

found this on Google for you (source here):

/// <summary>
/// Generates a random string with the given length
/// </summary>
/// <param name="size">Size of the string</param>
/// <param name="lowerCase">If true, generate lowercase string</param>
/// <returns>Random string</returns>
private string RandomString(int size, bool lowerCase)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch ;
for(int i=0; i<size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ;
builder.Append(ch); 
}
if(lowerCase)
return builder.ToString().ToLower();
return builder.ToString();
}

After that, use file streams to create and write the file.

怀念你的温柔 2024-08-08 22:56:59

查看 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.

北音执念 2024-08-08 22:56:59

如果您想自己创建文件名,请将要使用的字符放入字符串中并从中选择:

// 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)))

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)))
暗恋未遂 2024-08-08 22:56:59

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文