gaurav sachdeva gaurav sachdeva -4 years ago 99
C# Question

Extract the original file name

I have an application in which user has an option to attach a file. The file is then stored in the database and the file name is appended with a few strings such as form name, request number and date. I want to extract the original file name from this file.

eg. A file name Test_File.docx is saved as Test_File__ABC__123_01252017.docx. I have written a code to extract the file name using the code but I feel that there are many redundant elements in my code. Can someone please let me know if there is an alternative or a better way to write this.
Here is my piece of code.

file = "Test_File__ABC__123_01252017.docx";
int ix1 = file.LastIndexOf('_');
int ix2 = ix1 > 0 ? file.LastIndexOf('_', ix1 - 1) : -1;
int ix3 = ix2 > 0 ? file.LastIndexOf('_', ix2 - 1) : -1;
int ix4 = ix3 > 0 ? file.LastIndexOf('_', ix3 - 1) : -1;
int ix5 = ix4 > 0 ? file.LastIndexOf('_', ix4 - 1) : -1;
int ix6 = ix5 > 0 ? file.LastIndexOf('_', ix5 - 1) : -1;

string Real_Name = file.Substring(0, ix6);


Real_Name contains the original file name "Test_File"

Answer Source

You can try this:

string orgFileName = "Test_File__ABC__123__01252017.docx";
string[] fileNameParts = orgFileName.Split(new string[] { "__" }, StringSplitOptions.None);
string realFileName = string.Empty;

string realFileName = string.Empty;

for (int i = 0; i < fileNameParts.Length - 3; i++)
{
     realFileName += fileNameParts[i] + "__";
}

realFileName = realFileName.Substring(0, realFileName.Length - 2);

Or Even much simplier:

string orgFileName = "Test__File__ABC__123__01252017.docx";
string[] fileNameParts = orgFileName.Split(new string[] { "__" }, StringSplitOptions.None);
string result = String.Join("__", fileNameParts.Take(fileNameParts.Length - 3));     
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download