It seems a simple one but I confused to get it.
Here is the case:
I have a complete file name like abdcd.pdf
or efghijf.jpg
or jklmn.jpeg
,
Now I have to get only the file name as abdcd
or efghijf
or jklmn
It seems a simple one but I confused to get it.
Here is the case:
I have a complete file name like abdcd.pdf
or efghijf.jpg
or jklmn.jpeg
,
Now I have to get only the file name as abdcd
or efghijf
or jklmn
Use Path class static method
result = Path.GetFileNameWithoutExtension(fileName);
String f = "file.jpg";
int lastIndex = f.LastIndexOf('.');
Console.WriteLine(f.Substring(0, lastIndex));
Or, like the others suggested, you can also use
Path.GetFileNameWithoutExtension(f)
You could use String.Substring()
, but I recommend Path.GetFileNameWithoutExtension()
for this task:
// returns "test"
Path.GetFileNameWithoutExtension("test.txt")
This method is essentially implemented like this:
int index = path.LastIndexOf('.');
return index == -1 ? path : path.Substring(0, index);
I would use the API call.
http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension(v=vs.110).aspx
string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;
result = Path.GetFileNameWithoutExtension(fileName);
Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'",
fileName, result);
result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
path, result);
// This code produces output similar to the following:
//
// GetFileNameWithoutExtension('C:\mydir\myfile.ext') returns 'myfile'
// GetFileName('C:\mydir\') returns ''
There is actually a method for that:
http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension(v=vs.110).aspx
Use the GetFileNameWithoutExtension static method like this:
result = Path.GetFileNameWithoutExtension(fileName);
From the MSDN:
The string returned by GetFileName, minus the last period (.) and all characters following it.