How to generate a random named text file in C#?

杀马特。学长 韩版系。学妹 提交于 2019-12-05 07:50:00

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

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.

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.

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();
}

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!