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?
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:
// 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)))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With