How to get folder/directory path from input? - c#

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!

Related

FullName, FullPath for Directory

Why does a DirectoryInfo not provide a unified way to get the qualified name for a folder.
In this example:
class Program
{
static void Main(string[] args)
{
System.IO.DirectoryInfo DirInfo = new System.IO.DirectoryInfo(#"C:\TEMP\");
Console.WriteLine(DirInfo.FullName);
System.IO.DirectoryInfo DirInfo2 = new System.IO.DirectoryInfo(#"C:\TEMP");
Console.WriteLine(DirInfo2.FullName);
Console.ReadLine();
}
}
Regardless if the directory actually exists, the FullName just reflects the userinput into the object, but you can't be certain you get a path with a "\" in the end.
In the MSDN documentation there is mentioned a inheritance from FileSystemInfo, where there is the possibility to retrieve the FQN by the property FullPath, but I can't seem to access it from an instance of DirectoryInfo.
Is there maybe a trick, or another method / field to get to be sure that the path always have the same format?
There's no way or method to get the trailing backslash if it's not there. It's completely optional, but it also shouldn't make a difference for your program if it's there or not. But if you want to ensure it:
char[] blackslashes = {Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar};
string dirPath = #"C:\TEMP";
if (!blackslashes.Contains(dirPath.Last()))
dirPath += "\\";
System.IO.DirectoryInfo dirInfo = new System.IO.DirectoryInfo(dirPath);
I am not sure if i did understood your question correct ... but to get it unified, just use eg. a Sanitize method.
Example to always remove tailing backslash:
public string SanitizePath(string s) => s.TrimEnd('/', '\\');
Example to always add tailing backslash:
public string SanitizePath(string s) => s[s.Length - 1] == '/' || s[s.Length - 1] == '\\' ? s : String.Concat(s, '\\');
However, if the problem is invalid paths due to that inconsistency, chances are that you use String.Concat to build the full path.
You always should use Path.Combine for combining a path information as that should provide the proper output.

How to cut out a part of a path?

I want to cut out a part of a path but don't know how.
To get the path, I use this code:
String path = System.IO.Path.GetDirectoryName(fullyQualifiedName);
(path = "Y:\Test\Project\bin\Debug")
Now I need the first part without "\bin\Debug".
How can I cut this part out of the current path?
If you know, that you don't need only "\bin\Debug" you could use replace:
path = path.Replace("\bin\Debug", "");
or
path = path.Remove(path.IndexOf("\bin\Debug"));
If you know, that you don't need everything, after second \ you could use this:
path = path.Remove(path.LastIndexOfAny(new char[] { '\\' }, path.LastIndexOf('\\') - 1));
and finally, you could Take so many parts, how many you want like this:
path = String.Join(#"\", path.Split('\\').Take(3));
or Skip so many parts, how many you need:
path = String.Join(#"\", path.Split('\\').Reverse().Skip(2).Reverse());
You can use the Path class and a subsequent call of the Directory.GetParent method:
String dir = Path.GetDirectoryName(fullyQualifiedName);
string root = Directory.GetParent(dir).FullName;
You can do it within only 3 lines.
String path= #"Y:\\Test\\Project\\bin\\Debug";
String[] extract = Regex.Split(path,"bin"); //split it in bin
String main = extract[0].TrimEnd('\\'); //extract[0] is Y:\\Test\\Project\\ ,so exclude \\ here
Console.WriteLine("Main Path: "+main);//get main path
You can obtain the path of the parent folder of your path like this:
path = Directory.GetParent(path);
In your case, you'd have to do it twice.

Trying to delete multiple files from a single directory whose names match\contain a particular string

I wish to delete image files. The files are named somefile.jpg and somefile_t.jpg, the file with the _t on the end is the thumbnail. With this delete operation I wish to delete both the thumbnail and original image.
The code works up until the foreach loop, where the GetFiles method returns nothing.
The string.Substring operation successfully returns just the file name with no extension and no _t e.g: somefile.
There are no invalid characters in the file names I wish to delete.
Code looks good to me, only thing I can think of is that I am somehow not using the searchpattern
function properly.
filesource = "~/somedir/somefile_t.jpg"
var dir = Server.MapPath(filesource);
FileInfo FileToDelete = new FileInfo(dir);
if (FileToDelete.Exists)
{
var FileName = Path.GetFileNameWithoutExtension(FileToDelete.Name);
foreach(FileInfo file in FileToDelete.Directory.GetFiles(FileName.Substring(0, FileName.Length - 2), SearchOption.TopDirectoryOnly).ToList())
{
file.Delete();
}
}
DirectoryInfo.GetFiles Method (String, SearchOption)
You need to ensure that the first parameter, searchPattern, is proper. In you're case you are supplying FileName.Substring(0, FileName.Length - 2), which would be "somefile". The reason the method returns nothing is because you are looking for files literally named somefile. What you meant to do was to use a wildcard in addition to the base filename: String.Concat(FileName.Substring(0, FileName.Length - 2), "*"), which would be "somefile*" ... at least I think you're looking for that searchPattern as opposed to any other one.
This code works for me:
var file_path = #"K:\Work\IoCToy\IoCToy\image.jpg";
var dir = Path.GetDirectoryName(file_path);
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file_path);
var files = Directory.EnumerateFiles(dir, string.Format("{0}*", fileNameWithoutExtension), SearchOption.TopDirectoryOnly);
Of course, you have to delete the files by the returned file names. I am assuming here that your folder contains only the image and the thumbnail file which start with the "image" substring.

File names matching "..\ThirdParty\dlls\*.dll"

Is there an easy way to get a list of filenames that matach a filename pattern including references to parent directory? What I want is for "..\ThirdParty\dlls\*.dll" to return a collection like ["..\ThirdParty\dlls\one.dll", "..\ThirdParty\dlls\two.dll", ...]
I can find several questions relating matching files names including full path, wildcards, but nothing that includes "..\" in the pattern. Directory.GetFiles explicitly disallows it.
What I want to do with the names is to include them in a zip archive, so if there is a zip library that can understand relative paths like this I am happier to use that.
The pattern(s) are coming from an input file, they are not known at compile time. They can get quite complex, e.g ..\src\..\ThirdParty\win32\*.dll so parsing is probably not feasible.
Having to put it in zip is also the reason I am not very keen on converting the pattern to fullpath, I do want the relative paths in zip.
EDIT: What I am looking for really is a C# equivalent of /bin/ls.
static string[] FindFiles(string path)
{
string directory = Path.GetDirectoryName(path); // seperate directory i.e. ..\ThirdParty\dlls
string filePattern = Path.GetFileName(path); // seperate file pattern i.e. *.dll
// if path only contains pattern then use current directory
if (String.IsNullOrEmpty(directory))
directory = Directory.GetCurrentDirectory();
//uncomment the following line if you need absolute paths
//directory = Path.GetFullPath(directory);
if (!Directory.Exists(directory))
return new string[0];
var files = Directory.GetFiles(directory, filePattern);
return files;
}
There is the Path.GetFullPath() function that will convert from relative to absolute. You could use it on the path part.
string pattern = #"..\src\..\ThirdParty\win32\*.dll";
string relativeDir = Path.GetDirectoryName(pattern);
string absoluteDir = Path.GetFullPath(relativeDir);
string filePattern = Path.GetFileName(pattern);
foreach (string file in Directory.GetFiles(absoluteDir, filePattern))
{
}
If I understand you correctly you could use Directory.EnumerateFiles in combination with a regular expression like this (I haven't tested it though):
var matcher = new Regex(#"^\.\.\\ThirdParty\\dlls\\[^\\]+.dll$");
foreach (var file in Directory.EnumerateFiles("..", "*.dll", SearchOption.AllDirectories)
{
if (matcher.IsMatch(file))
yield return file;
}

Get folder name from full file path

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.

Categories

Resources