views:

1375

answers:

6

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?

+22  A: 

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.

Oren Trutner
+1 just what I was about to answer :-)
galaktor
+1  A: 

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.

Martin v. Löwis
+1  A: 

Hi, 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.

Thorsten Dittmar
+1 for answering the question.
Filmund
+3  A: 

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.

Jan Suvak
+2  A: 

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();
}
Zenuka
I've used this method many times. It's obviously not a '5 letter string' as requested but in Windows environment there doesn't seem to be any need to limit yourself to 5 letters. The benefit here is that it is 'guaranteed' to be unique (even if Wikipedia disagrees).BTW checking (File.Exists(filename)) is redundant because filename will not exist.
Kirk Broadhurst
Well, you never know - there might be a need for those 5 letter file names in case another tool processing these files requires the file names to be no longer than 5 letters. This would be a WTF on the other tool's developer's side, but the requirement is still there, so I in my opinion saying "You can use GUIDs - they're not 5 chars in length, but still" is like saying "Or you might as well just not create any file at all" - both doesn't solve his problem :-D
Thorsten Dittmar
+4  A: 

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(folderPath + name))
Guffa