Get contents after last slash - c#

I have strings that have a directory in the following format:
C://hello//world
How would I extract everything after the last / character (world)?

string path = "C://hello//world";
int pos = path.LastIndexOf("/") + 1;
Console.WriteLine(path.Substring(pos, path.Length - pos)); // prints "world"
The LastIndexOf method performs the same as IndexOf.. but from the end of the string.

using System.Linq;
var s = "C://hello//world";
var last = s.Split('/').Last();

There is a static class for working with Paths called Path.
You can get the full Filename with Path.GetFileName.
or
You can get the Filename without Extension with Path.GetFileNameWithoutExtension.

Try this:
string worldWithPath = "C://hello//world";
string world = worldWithPath.Substring(worldWithPath.LastIndexOf("/") + 1);

I would suggest looking at the System.IO namespace as it seems that you might want to use that. There is DirectoryInfo and FileInfo that might be of use here, also. Specifically DirectoryInfo's Name property
var directoryName = new DirectoryInfo(path).Name;

Related

Remove Extra back slash "\" from string file path in c#

How to convert
"String path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
into
String path = #"C:\Abc\Omg\Why\Me\".
My approach is to first reverse the string and then remove all the "\" till we get first char, and the reverse it again.
How to do this in C#, is there any method for such operation?
You can just construct path using the Path static class:
string path = Path.GetFullPath(#"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\");
After this operation, variable path will contain the minimal version:
C:\Abc\Omg\Why\Me\
You can use path.TrimEnd('\\'). Have a look at the documentation for String.TrimEnd.
If you want the trailing slash, you can add it back easily.
var path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = path.TrimEnd('\\') + '\\';
another solution is
var path = #"C:\Abc\Omg\Why\Me\\\\\\\\\\\\\\\\\\\\\";
path = Path.GetFullPath(path);

Path.Combine() returns unexpected results

I'm trying to create a path using Path.Combine() but I am getting unexpected results.
using System;
using System.IO;
namespace PathCombine_Delete
{
class Program
{
static void Main(string[] args)
{
string destination = "D:\\Directory";
string destination02 = "it";
string path = "L:\\MyFile.pdf";
string sourcefolder = "L:\\";//In other instances, it could be L:\\SomeFolder\AndMayBeAnotherFolder
string replacedDetails = path.Replace(sourcefolder + "\\", "");
string result = Path.Combine(destination, destination02, replacedDetails);
Console.WriteLine(result);
Console.ReadKey();//Keep it on screen
}
}
}
I would expect the result D:\\Directory\it\MyFile.pdf but instead, I get L:\MyFile.pdf
I can't see why? I admit it's late in the evening here, but still, I've used Path.Combine many times, and since .NET 4.0 it allows the string param to be passed. However, it appears to be ignoring the first 2 and only reading the last.
Here is the error
string replacedDetails = path.Replace(sourcefolder + "\\" , "");
You are adding another backslash and nothing is found to be replaced.
Removing the added backslash gives the correct string to search for and replace
string replacedDetails = path.Replace(sourcefolder , "");
however you could avoid all that replace stuff and intermediate variables just with
string result = Path.Combine(destination, destination02, Path.GetFileName(path));
I would recommend using:
string replacedDetails = Path.GetFileName(path);
That will handle removing the source folder from the path without using string replacement, which isn't necessarily reliable if you're getting the path from elsewhere (eventually).
Have you read the documentation? Have you verified what you're passing to Path.Combine()? The documentation says, and I quote:
path1 should be an absolute path (for example, "d:\archives" or "\archives\public").
If path2 or path3 is also an absolute path, the combine operation discards all
previously combined paths and resets to that absolute path.
That should hint at the problem.

c# how to get one value from substring

How to solve this?
What i want to change this :
C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\
to new value:
value = "1.0.11";
You could just get the Name of the corresponding DirectoryInfo:
string path = #"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";
string version = new DirectoryInfo(path).Name;
Alternative method:
var path = #"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";
var value = Path.GetFileName(path.TrimEnd(new[]{'/','\\'}));
// OUTPUT: 1.0.1.1
This basically removes any last directory delimeters and then treats the last directory as a filename, so it returns the last directory.
Based on #JeppeStigNielsen's comments below, here's a better, platform independent alternative.
var value = Path.GetFileName(Path.GetDirectoryName(path));
This will work if there is a file name present as well.
var value = Path.GetFileName(Path.GetDirectoryName(".../1.0.1.1/somefile.etc"));
// returns 1.0.1.1
Darin's answer is great but as an alternative;
string s = #"C:\files\team\business\dev\Source\systems\extension\destination\1.0.1.1\";
string[] array = s.Split('\\');
Console.WriteLine(array[array.Length - 2]);
Output will be;
1.0.1.1
Here a DEMO.

How to get the second to last directory in a path string in C#

For example,
string path = #"C:\User\Desktop\Drop\images\";
I need to get only #"C:\User\Desktop\Drop\
Is there any easy way of doing this?
You can use the Path and Directory classes:
DirectoryInfo parentDir = Directory.GetParent(Path.GetDirectoryName(path));
string parent = parentDir.FullName;
Note that you would get a different result if the path doesn't end with the directory-separator char \. Then images would be understood as filename and not as directory.
You can also use a subsequent call of Path.GetDirectoryName
string parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
This behaviour is documented here:
Because the returned path does not include the DirectorySeparatorChar
or AltDirectorySeparatorChar, passing the returned path back into the
GetDirectoryName method will result in the truncation of one folder
level per subsequent call on the result string. For example, passing
the path "C:\Directory\SubDirectory\test.txt" into the
GetDirectoryName method will return "C:\Directory\SubDirectory".
Passing that string, "C:\Directory\SubDirectory", into
GetDirectoryName will result in "C:\Directory".
This will return "C:\User\Desktop\Drop\" e.g. everything but the last subdir
string path = #"C:\User\Desktop\Drop\images";
string sub = path.Substring(0, path.LastIndexOf(#"\") + 1);
Another solution if you have a trailing slash:
string path = #"C:\User\Desktop\Drop\images\";
var splitedPath = path.Split('\\');
var output = String.Join(#"\", splitedPath.Take(splitedPath.Length - 2));
var parent = "";
If(path.EndsWith(System.IO.Path.DirectorySeparatorChar) || path.EndsWith(System.IO.Path.AltDirectorySeparatorChar))
{
parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
parent = Directory.GetParent(Path.GetDirectoryName(path)).FullName;
}
else
parent = Path.GetDirectoryName(path);
As i commented GetDirectoryName is self collapsing it returns path without tralling slash - allowing to get next directory.Using Directory.GetParent for then clouse is also valid.
Short Answer :)
path = Directory.GetParent(Directory.GetParent(path)).ToString();
Example on the bottom of the page probably will help:
http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname(v=vs.110).aspx
using System;
namespace Programs
{
public class Program
{
public static void Main(string[] args)
{
string inputText = #"C:\User\Desktop\Drop\images\";
Console.WriteLine(inputText.Substring(0, 21));
}
}
}
Output:
C:\User\Desktop\Drop\
There is probably some simple way to do this using the File or Path classes, but you could also solve it by doing something like this (Note: not tested):
string fullPath = "C:\User\Desktop\Drop\images\";
string[] allDirs = fullPath.split(System.IO.Path.PathSeparator);
string lastDir = allDirs[(allDirs.length - 1)];
string secondToLastDir= allDirs[(allDirs.length - 2)];
// etc...

Do I use a regular expression on this file path?

I have to strip a file path and get the parent folder.
Say my path is
\\ServerA\FolderA\FolderB\File.jpg
I need to get
File Name = File.jog
Folder it resides in = FolderB
And parent folder = FolderA
I always have to go 2 levels up from where the file resides.
Is there an easier way or is a regular expression the way to go?
FileInfo is your friend:
using System;
using System.IO;
class Test
{
static void Main(string[] args)
{
string file = #"\\ServerA\FolderA\FolderB\File.jpg";
FileInfo fi = new FileInfo(file);
Console.WriteLine(fi.Name); // Prints File.jpg
Console.WriteLine(fi.Directory.Name); // Prints FolderB
Console.WriteLine(fi.Directory.Parent.Name); // Prints FolderA
}
}
string fileName = System.IO.Path.GetFileName(path);
string parent = System.IO.Path.GetDirectoryName(path);
string parentParent = System.IO.Directory.GetParent(parent);
Check out the Directory class (better choice than DirectoryInfo in this case). It does everything you need. You should not use a regex or any other parsing technique.
var fi = new FileInfo(#"\\ServerA\FolderA\FolderB\File.jpg");
fi.Name
fi.Directory.Name
fi.Directory.Parent.Name
You have a few options to do this actually which use actual .net objects instead of regex.
You can use the FileInfo:
FileInfo fileInfo = new FileInfo(#"\\ServerA\FolderA\FolderB\File.jpg");
fileInfo.Name //will give you the file name;
DirectoryInfo directory = fileInfo.Directory; //will give you the parent folder of the file (FolderB);
directory.Parent; //will give you this directories parent folder (FolderA)
If you know for sure that you are always dealing with a file and two directories, try using split:
string s = #"\\ServerA\FolderA\FolderB\File.jpg";
string[] parts = s.Split('\'); // might need '\\'
string file = parts[parts.Length];
string parentDir = parts[parts.Length - 1];
string grandParentDir = parts[parts.Length - 2];

Categories