Getting File name from the String - c#

Could you help me for finding the file name from the string. Now i have one string of content like "C:\xxxx\xxxx\xxxx\abc.pdf". But i want only the file name ie. abc.pdf. How it will get by using string functions?

Use Path.GetFileName:
string full = #"C:\xxxx\xxxx\xxxx\abc.pdf";
string file = Path.GetFileName(full);
Console.WriteLine(file); // abc.pdf
Note that this assumes the last part of the name is a file - it doesn't check. So if you gave it "C:\Windows\System32" it would claim a filename of System32, even though that's actually a directory. (Passing in "C:\Windows\System32\" would return an empty string, however.) You can use File.Exists to check that a file exists and is a file rather than a directory if that would help.
This method also doesn't check that all the other elements in the directory hierarchy exist - so you could pass in "C:\foo\bar\baz.txt" and it would return baz.txt even if foo and bar don't exist.

Use the Path.GetFileName() Method
(Edited) sample from the MSDN-page:
string fileName = #"C:\xxxx\xxxx\xxxx\abc.pdf";
string path = #"C:\xxxx\xxxx\xxxx\";
string path2 = #"C:\xxxx\xxxx\xxxx";
string result;
result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
fileName, result);
result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
path, result);
result = Path.GetFileName(path2);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
path2, result);
This code produces output similar to the following:
GetFileName('C:\xxxx\xxxx\xxxx\abc.pdf') returns 'abc.pdf'
GetFileName('C:\xxxx\xxxx\xxxx\') returns ''
GetFileName('C:\xxxx\xxxx\xxxx') returns 'xxxx'

Sytem.IO.FileInfo is also quite cool:
In your case you can do
FileInfo fi = new FileInfo("C:\xxxx\xxxx\xxxx\abc.pdf");
string name = fi.Name; // it gives you abc.pdf
Then you can have several other pieces of information:
does the file really exist? fi.Exists gives you the answer
what's its extension? see fi.Extension
what's the name of its directory? see fi.Directory
etc.
Have a look at all the members of FileInfo you may find something interesting for your needs

Use the methods of System.IO.Path, especially
Path.GetFileName.

System.IO.Path.GetFilename(yourFilename)
will return the name of the file.

You could use System.IO.Path.GetFileNameWithoutExtension(string path):
System.IO.Path.GetFileNameWithoutExtension("C:\xxxx\xxxx\xxxx\abc.pdf")
And you would get back abc

Related

Creating copy of a file at one position up in the same folder/directory location

I have a Path;
\\\\username-txd\location\Configuration\MediaManagerConfig\Web.config
I want to create a copy of file at one position up in the same folder i.e.
\\\\username-txd\location\Configuration\Web.config
Can anyone help me with the code since I am new to C#
DirectoryInfo.Parent returns this MediaManagerConfig and you can do little bit string manupalition like;
var di = new DirectoryInfo(#"\\\\username-txd\location\Configuration\MediaManagerConfig\Web.config");
Console.WriteLine(di.FullName.Replace(di.Parent.Name + Path.DirectorySeparatorChar, ""));
Result will be;
\\username-txd\location\Configuration\Web.config
If you want 4 back slash based on your result, your can replace with \\ to \\\\ as well.
You can use File.Copy to copy the file.
To get your destination file name, you can do
Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(path)), Path.GetFileName(path));
with 'path' the full path with the file name.
You need to import System.IO.
I would use seomthing like the power of the DirectoryInfo class. It knows the relationship on the filesystem and provides e.g. the .Parent property:
string originalFilename = "\\\\username-txd\\location\\Configuration\\MediaManagerConfig\\Web.config";
string originalPath = Path.GetDirectoryName(originalFilename);
string newPath = Path.Combine(new DirectoryInfo(originalPath).Parent.FullName, Path.GetFileName(originalFilename));

How can I get a 'File Name' ONLY from the (File Name + Extension) using substring in C#? [duplicate]

This question already has answers here:
Getting file names without extensions
(14 answers)
Closed 9 years ago.
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")
Go to the msdn documentation
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 ''
I would use Path static method: Path.GetFileNameWithoutExtension()
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.

read file name and find particular string

I have filename like
ChrysanthemumThumbnail82b09296a7c34373833050d362745a30.jpg
How can I find this string ChrysanthemumThumbnail
You can use Path.GetFileNameWithoutExtension method to read the file name without extension and then you can use string.Contains to check if it contains your string.
string fileName = Path.GetFileNameWithoutExtension("ChrysanthemumThumbnail82b09296a7c34373833050d362745a30.jpg");
if(fileName.Contains("ChrysanthemumThumbnail"))
{
//name found
}
if you want to see if the fileName starts with your string then you can use string.StartsWith
if(fileName.StartsWith("ChrysanthemumThumbnail"))
{
//file name starts with ChrysanthemumThumbnail
}
(if you have the FileName already in a string then you don't need Path.GetFileNameWithoutExtension it is only useful if you are trying to extract the filename from a path)
Did you want something like:
string filename = "ChrysanthemumThumbnail82b09296a7c34373833050d362745a30.jpg"
bool result = filename.Contains("ChrysanthemumThumbnail");
if the ChrysanthemumThumbnail always at start of the filename then just use 'StartWith'
, this will have better over contains which checks whole string
"ChrysanthemumThumbnail82b09296a7c34373833050d362745a30.jpg".StartsWith("ChrysanthemumThumbnail")
and if it can be at any location than use contains as suggested by Habib above
"ChrysanthemumThumbnail82b09296a7c34373833050d362745a30.jpg".Contains ("ChrysanthemumThumbnail")

How to get folder/directory path from input?

How do you get the last folder/directory out of user-input regardless of if the input is a path to a folder or a file? This is when the folder/file in question may not exist.
C:\Users\Public\Desktop\workspace\page0320.xml
C:\Users\Public\Desktop\workspace
I'm trying to get out the folder "workspace" out of both examples, even if the folder "workspace" or file "page0320.xml" doesn't exist.
EDIT: Using BrokenGlass's suggestion, I got it to work.
String path = #"C:\Users\Public\Desktop\workspace";
String path2 = #"C:\Users\Public\Desktop\workspace\";
String path3 = #"C:\Users\Public\Desktop\workspace\page0320.xml";
String fileName = path.Split(new char[] { '\\' }).Last<String>().Split(new char[] { '/' }).Last<String>();
if (fileName.Contains(".") == false)
{
path += #"\";
}
path = Path.GetDirectoryName(path);
You can substitute any of the path variables and the output will be:
C:\Users\Public\Desktop\workspace
Of course, this is working under the assuption that files have extensions. Fortunately, that assumption works for my purposes.
Thanks all. Been a long-time lurker and first-time poster. It was really impressive how fast and helpful the responses were :D
use Path.GetDirectoryName :
string path = Path.GetDirectoryName(#"C:\Users\Public\Desktop\workspace\page0320.xml");
string path2 = Path.GetDirectoryName(#"C:\Users\Public\Desktop\workspace\");
Note the trailing backslash in the path though in the second example - otherwise workspace will be interpreted as file name.
I will use DirectoryInfo in this way:
DirectoryInfo dif = new DirectoryInfo(path);
if(dif.Exist == true)
// Now we have a true directory because DirectoryInfo can't be fooled by
// existing file names.
else
// Now we have a file or directory that doesn't exist.
// But what we do with this info? The user input could be anything
// and we cannot assume that is a file or a directory.
// (page0320.xml could be also the name of a directory)
You can use GetFileName after GetDiretoryName from the Path class in the System.IO namespace.
GetDiretoryName will get the path without the filename (C:\Users\Public\Desktop\workspace).
GetFileName then returns the last part of the path as if it is a extensionless file (workspace).
Path.GetFileName(Path.GetDirectoryName(path));
EDIT: the path must have a trailing path separator to make this example work.
If you can make some assumptions then its pretty easy..
Assumption 1: All files will have an extension
Assumption 2: The containing directory will never have an extension
If Not String.IsNullOrEmpty(Path.GetExtension(thePath))
Return Path.GetDirectoryName(thePath)
Else
Return Path.GetFileName(thePath)
End If
Like said before, there's not really a feasible solution but this might also do the trick:
private string GetLastFolder(string path)
{
//split the path into pieces by the \ character
var parts = path.Split(new[] { Path.DirectorySeparatorChar, });
//if the last part has an extension (is a file) return the one before the last
if(Path.HasExtension(path))
return parts[parts.Length - 2];
//if the path has a trailing \ return the one before the last
if(parts.Last() == "")
return parts[parts.Length - 2];
//if none of the above apply, return the last element
return parts.Last();
}
This might not be the cleanest solution but it will work. Hope this helps!

How to get the relative filename to a specific directory?

I have a method which is doing a file copy. The 'root' is specified by the user on the command line, which I sanitize with Path.GetFullPath(input).
I need to get the path of the file relative to that root, so the following cases would return:
Root FilePath Return
y:\ y:\temp\filename1.txt temp\filename1.txt
y:\dir1 y:\dir1\dir2\filename2.txt dir2\filename2.txt
You can write
var relative = new Uri(rootPath).MakeRelativeUri(new Uri(filePath));
http://msdn.microsoft.com/en-us/library/system.uri.makerelativeuri.aspx
string s1 = "y:\\";
string s2 = "y:\\temp\filename1.txt";
Console.WriteLine(s2.Substring(s1.Length)); \\ Outputs temp\filename1.txt
Hope this helps
Might want to call a .Trim() as well to ensure removing trailing \ characters or the like.
System.IO.Path.GetFullPath( filePath ).Substring( rootPath.Length )
string relativePath = Path.GetFullPath(input).Replace(rootPath, "");

Categories

Resources