I want to upload files to a web server in a C# project and I already use GUID to get unique filenames. The only problem is that this way I can upload the same file multiple times and always with a different filename.
I would like to find a way to give a file a unique name but always the same, so if I try to upload it again it will have the same filename and I get a message that it already exists.
Any ideas on that?
Asked
Active
Viewed 558 times
1

Ivar
- 6,138
- 12
- 49
- 61

V. Vouvonikos
- 63
- 2
- 9
-
6name them according to the MD5 checksum, or SHA-2 if you're paranoid. – Alex Jan 14 '16 at 13:22
-
Whoops, you were faster – Jan 14 '16 at 13:24
-
thanks guys, thumbs up! – V. Vouvonikos Jan 14 '16 at 13:27
2 Answers
4
Creating MD5 checksums for your files and using them as filename.
-
1MD5 checksums should work for this, but aware that there are potential performance issues if the files are large. [This stack overflow question describes][1] how to avoid those issues. [1]: http://stackoverflow.com/questions/1177607/what-is-the-fastest-way-to-create-a-checksum-for-large-files-in-c-sharp – tomRedox Jan 14 '16 at 13:29
2
Use the following code to generate the file name. ComputeHash will generate the hash and GetString will convert the byte array to string.
using (var md5 = MD5.Create())
{
using (var stream = new BufferedStream(File.OpenRead(myFile)))
{
return string.Concat(md5.ComputeHash(stream));
}
}

Radin Gospodinov
- 2,313
- 13
- 14