views:

423

answers:

8

when I add a picture I want it to create a new random name because if you add a picture with the same name it will just overwrite

A: 

Perhaps you are looking for GetTempFileName.

Oded
This creates a file in $Env:TEMP and passes you its name. If the OP doesn't want the file there or would like another extension that's not the right thing to do.
Joey
@Johannes Rössel - I know it does, however the question is vague that I don't know what he actually wants.
Oded
Picture files generally don't end in `.tmp` or reside in $Env:TEMP. I would just apply common sense and a few heuristics ;-)
Joey
With 4 upvotes (at this time) on the question, it can't be that vague...
awe
+3  A: 

You could generate a Guid and use that for your file name. Although this would mean that the files are not human readable and have no information as to what the content is.

Matt
this worked for me thanks
saadan
+3  A: 

You could built it using current time.

string fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".png";

The above example will format the current time using Year, Month, Day, Hours, Minutes, Seconds, and Fractions of a second. (The fraction of a second can be specified with fewer fs if you want down to one.).


Advantages:

  • It will sort automatically by the created time in an alphabetically sorted list. ( like default sorting in file explorer ).
  • It is human readable and provides useful info about the time it is created.

Disadvantages:

  • If this is a web application (or other sort of multi-thread process) it is a (small) chance of two files getting same name if generated at the same time. This is not an issue if this is a single thread exe.
awe
This is better than using a GUID, as long as nobody changes the system time... ;-)
Treb
And what happens if two different processes/threads try to save at exactly the same instant in time?
LukeH
try it out, if can't be saved, create a new date etc?
PoweRoy
The fractions don't buy you much here. The resolution you get from DateTime is usually 16 ms. You can stuff in more accuracy than that but that's not what you get out of the system time. You may resort to the high-performance counter, though.
Joey
@Johannes: I agree with you that 6 decimals on the fraction is overkill. I didn't know what resolution you get from the system clock, so I just suggested the max resolution available in the time format function. I have edited my answer to include only 3 f's, which is down to milliseconds.
awe
@Luke: With Milliseconds in the stamp, it's like hitting a jackpot.
Bobby
@Luke (and @PoweRoy): If this can potentially be an issue, I think another approach will be better. But this is something the developer need to consider in each case. If this is a web application, it might be an issue, but if it is a standalone exe, it will be no problem.
awe
@Bobby: If this is a web application with a lot of traffic, the chance of *hitting the jackpot* rises significantly.
awe
+2  A: 

Name your image using a GUID

For C# you can use: System.Guid.NewGuid().ToString()

hakan
A: 

i would go with awe use original filename + DateTime.Now.ToString("yyyyMMddHHmmssffff");

swirm
+5  A: 

As you want to save pictures, you could just use a GUID as the filename:

string filename = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + ".jpg");

I always do it this way when I need another file extension than .tmp (which files get when you create them via GetTempFileName).
Of course you could create the files via GetTempFileName and then rename them, but then you have to check again if a file with the new name exists...

haarrrgh
A: 

I would also go with the GUID solution.

Here some code I would use regularly:

public static string GetRandomFileName(string extension)
{
    StringBuffer sb = new StringBuffer(Guid.NewGuid().ToString());
    if (!string.IsNullOrEmpty(extensions))
    {
        sb.Append(".");
        sb.Append(extension);
    }

    return sb.ToString();
}

Would provide you with a fine, reusable solution. Put this into your "collection of my greatest moments" - classlibrary and you are good to go.

stormianrootsolver
You don't need a StringBuilder in this case, it's probably SLOWER than regular string functions.
Hans Kesting
I assume you mean to use `StringBuilder` (`StringBuffer` is more Java...). If you want to take full advantage of the StringBuilder, you need to initialize it with the size you are going to use. In this case you know the full length of the resulting string, so you can take advantage of that: `StringBuffer sb = new StringBuilder(Guid.NewGuid().ToString("N"), 33 + extension.Length);` or if you can make the assumption that the extension is 3 chars: `StringBuffer sb = new StringBuilder(Guid.NewGuid().ToString("N"), 36);`.
awe
Sorry, I got that wrong, of course it's StringBuilder.Reason I use it here is that I think it's always preferable to use the same way of coding something over and over again.Should performance problems arise, there is still time to modify the code (optimization), but I don't think that this routine will be the make - or - break - factor.Thank you very much, however, for the inspirational idea with the buffer size!
stormianrootsolver
+1  A: 

The are built-in method Path.GetRandomFileName. It returns a random folder name or file name.

The GetRandomFileName method returns a cryptographically strong, random string that can be used as either a folder name or a file name. Unlike GetTempFileName, GetRandomFileName does not create a file. When the security of your file system is paramount, this method should be used instead of GetTempFileName.

If you want to use your extension (e.g. .jpg instead of generated), you could add it to generated file as:

string extension = ".jpg";
string fileName = Path.GetRandomFileName() + extension;
Alex