In many cases of file manipulation or validation, you will need to get the file name, file name without extension and especially with file extension when check an uploaded file on the fly or scan your project files.
By using the System.IO namespace, we don’t need to program to parse the string of file name or use any kind of substring or split function. The Path class in the namespace has 3 functions: GetExtension(), GetFileName(), GetFileNameWithoutExtension() to do that quickly and save a lot of time for you.
1. C# Get File Extension
string ext = System.IO.Path.GetExtension(Server.MapPath("members.xls")); Response.Write("ext: " + ext + "<br>"); // .xls |
2. C# Get File Name
string ext = System.IO.Path.GetFileName(Server.MapPath("members.xls")); Response.Write("file name: " + file_name+ "<br>"); // members.xls |
3. C# Get File Name Without Extension
string ext = System.IO.Path.GetFileNameWithoutExtension(Server.MapPath("members.xls")); Response.Write("file name without extension: " + file_name_without_extension+ "<br>"); // members |