Click here to Skip to main content
16,011,702 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please see below the code snippet. I had uploaded files & saved in physical folder with guid appended to the file name. Please see below. My purpose is to get back the file names without guid as shown below.
C#
HttpPostedFile PostedFile = Request.Files[i];
if (PostedFile.ContentLength > 0)
{
    Guid guid = Guid.NewGuid();
    string fileNameOrg = Path.GetFileName(PostedFile.FileName);
    string extention = Path.GetExtension(fileNameOrg);
    string fileNameNew = fileNameOrg.Replace(extention, "") + guid + extention;
    PostedFile.SaveAs(path + @"\" + fileNameNew);
}

SAVED FILE NAME : text1eb4617fd-4876-4c52-aa5b-21f8be8fb0f8.txt
SAVED FILE NAME : text296a712ff-efd9-4ab9-9f38-801e0fd23272.txt

Now My purpose is to extract only the file name without GUID
That is

OUTPUT FILE NAME : text1.txt
OUTPUT FILE NAME : text2.txt

Thanks in advance.
Posted
Updated 14-Oct-15 1:37am
v2
Comments
ZurdoDev 14-Oct-15 8:20am    
If you need it at the same time as the above code then the answer is obvious, store the filename in a separate variable before adding in GUID.

If you need it after the fact, later on, then I suggest parsing it. You could do regex or you could save the file name with a dash between name and GUID and then you can get everything before the first dash, for example.
Richard MacCutchan 14-Oct-15 8:32am    
Since you know the length of the GUID, it is a simple matter to strip those characters from the filename.

Easy:
C#
string inp = "text1eb4617fd-4876-4c52-aa5b-21f8be8fb0f8.txt";
const int guidLen = 36;
int extLen = inp.Length - inp.LastIndexOf('.');
string filename = inp.Substring(0, inp.Length - (extLen + guidLen)) + Path.GetExtension(inp);
 
Share this answer
 
To make things more efficient, you might reconsider saving the file name as follows:

string fileName = Guid.NewGuid().ToString() + "-" + Path.GetFileName(PostedFile.FileName);

That way, to determine the original uploaded file name later, all you need is the substring starting at the end of the guid and dash.

The reason I say this - imagine 1,000,000 users uploading 10 files each at the same time :-)

Rene.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900