gaurav sachdeva
gaurav sachdeva

Reputation: 57

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"

Upvotes: 0

Views: 211

Answers (2)

daniell89
daniell89

Reputation: 2282

You can try this:

string orgFileName = "Test__File__ABC__123__01252017.docx";
string[] fileNameParts = orgFileName.Split(new string[] { "__" }, StringSplitOptions.None);
string Real_Name = String.Join("__", fileNameParts.Take(fileNameParts.Length - 3));     

Upvotes: 1

Daniel Möller
Daniel Möller

Reputation: 86650

file = "Test_File__ABC__123_01252017.docx";
            int ix1 = file.LastIndexOf("__");
            int ix2 = ix1 > 0 ? file.LastIndexOf("__", ix1 - 1) : -1;

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

Please notice that this: "__" is different from this '__'.

This is string: "__"
This is char: '_'

Upvotes: 0

Related Questions