How to get the relative filename to a specific directory? - c#

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, "");

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 we remove certain folder name from the path and return new path?

I have a path:
"C:\\Users\\dev\\Test\\TestResults\\Config\\Report.xml"
I need to check if this path has folder "TestResults", if it has then I need to remove this and return new path as
"C:\\Users\\dev\\Test\\Config\\Report.xml"
I know I can achieve this using trim and split. But just to make sure I pick up a right choice. What is the best way of achieving this?
Any help really appriciated.
i would not use string replace method in this case. Why?
e.g. :
string path = "C:\\Users1\\Users2\\Users122\\Users13\\Users133\\filename.xml";
path = path.Replace("\\TestResults", string.Empty);
// you will get "C:\Users222333\filename.xml"
that is not what you expected.
so how to fix this,
path = string.Join(Path.DirectorySeparatorChar.ToString(),
path.Split(Path.DirectorySeparatorChar).Where(x=> x!="Users1").ToArray()));
//C:\Users2\Users122\Users13\Users133\filename.xml
You can use String.Replace method like;
Returns a new string in which all occurrences of a specified Unicode
character or String in the current string are replaced with another
specified Unicode character or String.
string path = "C:\\Users\\dev\\Test\\TestResults\\Config\\Report.xml";
path = path.Replace("\\TestResults", string.Empty);
Console.WriteLine(path);
Output will be;
C:\Users\dev\Test\Config\Report.xml
Here a DEMO.

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.

Using Substring in C# reverse

And I have filepath say "\ABC\ABX\file.pdf".
How can I get only the folder path i.e. "\ABC\ABX\" using substring any other way.
Thank you in advance.
Use System.IO.Path class
var dir = Path.GetDirectoryName(#"\ABC\ABX\file.pdf");
You're looking for Path.GetDirectoryName
var directoryOnly = System.IO.Path.GetDirectoryName(#"\ABC\ABX\file.pdf")
Live example: http://rextester.com/WDVD42852
You can do this using a combination of Substring and LastIndexOf:
string path = #"\ABC\ABX\file.pdf";
string directory = path.Substring(0, path.LastIndexOf(#"\") + 1);
It would also be ideal to add a check to ensure that the path even contains a \, and because of the + 1 you would also want to check that the \ is not already the last character. Of course though, it would be better to not need such string manipulation in the first place, but I don't know what your exact scenario is
string result = test.Substring(0, test.LastIndexOf("\\") + 1);
There are nicer ways to do this using System.IO, but purely string manipulation:
string path = #"\ABC\ABX\file.pdf";
string folder = path.Substring(0, path.LastIndexOf(#"\"));

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