How do I get the folder name from the full path of the application?
This is the开发者_运维知识库 file path below,
c:\projects\root\wsdlproj\devlop\beta2\text
Here "text" is the folder name.
How can I get that folder name from this path?
See DirectoryInfo.Name:
string dirName = new DirectoryInfo(@"c:\projects\roott\wsdlproj\devlop\beta2\text").Name;
I think you want to get parent folder name from file path. It is easy to get.
One way is to create a FileInfo
type object and use its Directory
property.
Example:
FileInfo fInfo = new FileInfo("c:\projects\roott\wsdlproj\devlop\beta2\text\abc.txt");
String dirName = fInfo.Directory.Name;
Try this
var myFolderName = @"c:\projects\roott\wsdlproj\devlop\beta2\text";
var result = Path.GetFileName(myFolderName);
You could use this:
string path = @"c:\projects\roott\wsdlproj\devlop\beta2\text";
string lastDirectory = path.Split(new char[] { System.IO.Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries).Last();
Simply use Path.GetFileName
Here - Extract folder name from the full path of a folder:
string folderName = Path.GetFileName(@"c:\projects\root\wsdlproj\devlop\beta2\text");//Return "text"
Here is some extra - Extract folder name from the full path of a file:
string folderName = Path.GetFileName(Path.GetDirectoryName(@"c:\projects\root\wsdlproj\devlop\beta2\text\GTA.exe"));//Return "text"
I figured there's no way except going into the file system to find out if text.txt is a directory or just a file. If you wanted something simple, maybe you can just use:
s.Substring(s.LastIndexOf(@"\"));
In this case the file which you want to get is stored in the strpath variable:
string strPath = Server.MapPath(Request.ApplicationPath) + "/contents/member/" + strFileName;
Here is an alternative method that worked for me without having to create a DirectoryInfo object. The key point is that GetFileName()
works when there is no trailing slash in the path.
var name = Path.GetFileName(path.TrimEnd(Path.DirectorySeparatorChar));
Example:
var list = Directory.EnumerateDirectories(path, "*")
.Select(p => new
{
id = "id_" + p.GetHashCode().ToString("x"),
text = Path.GetFileName(p.TrimEnd(Path.DirectorySeparatorChar)),
icon = "fa fa-folder",
children = true
})
.Distinct()
.OrderBy(p => p.text);
This can also be done like so;
var directoryName = System.IO.Path.GetFileName(@"c:\projects\roott\wsdlproj\devlop\beta2\text");
Based on previous answers (but fixed)
using static System.IO.Path;
var dir = GetFileName(path?.TrimEnd(DirectorySeparatorChar, AltDirectorySeparatorChar));
Explanation of GetFileName
from .NET source:
Returns the name and extension parts of the given path. The resulting string contains the characters of path that follow the last backslash ("\"), slash ("/"), or colon (":") character in path. The resulting string is the entire path if path contains no backslash after removing trailing slashes, slash, or colon characters. The resulting string is null if path is null.
精彩评论