Double separator in the path after Path.GetDirectoryName method c# - c#

I want get directory from blob absolute Uri:
https://001.blob.core.windows.net/files/11-files.trg.
For this I use Path.GetDirectoryName method. As result I have:
https:\\001.blob.core.windows.net\\files.
Why does a double separator appear and how to replace it with a single one?

I think Path.GetDirectoryName only works for relative paths, but not for URLs. So the first thing that comes to my mind is something like this:
var url = "https://001.blob.core.windows.net/files/11-files.trg";
var temp = new string(url.ToCharArray().Reverse().ToArray());
int index = temp.IndexOf('/');
temp = temp.Substring(index + 1 , temp.Length - index - 1);
var result = new string(temp.ToCharArray().Reverse().ToArray());
Console.WriteLine(result);
//output: https://001.blob.core.windows.net/files

Related

C# read path withoutI put / in each subfolder

I want to put file path in File.Copy(path)
How can I put the path and not add / every time?
In python I can put r to read the path and not add /:
open(r"path")
Is there anything similar in C Sharp?
Yes you can use the # operator: var path = #"c:\\APath\bier";
these are called verbatim strings:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#regular-and-verbatim-string-literals
Edit:
Also when dealing with paths string interpolation may come in handy, in short its a way to substitute values in a string. Its the same as string.format but the syntax is better imo:
var hello = "Hello";
var world = "world";
var helloworldStringFormat = string.Format("{0} {1}", hello, world);
var helloworldStringInterpolation = $"{hello} {world}";
Also see: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#string-interpolation
Any ways you can do things like this:
var someValue = "bier";
var path3 = $"c:\\APath\\{someValue}";
var path4 = string.Format(#"c:\APath\{0}", someValue);
Also check out the Path class for dealing with paths, and optionally the Directory class.
https://learn.microsoft.com/en-us/dotnet/api/system.io.path?view=net-5.0
https://learn.microsoft.com/en-us/dotnet/api/system.io.directory?view=net-5.0

How get a substring after the 3rd occurrence of a string c#

How can I find use the substring method so I can get everything after the 3rd occurence of "/"
for example I have string that contains: http://TEST.COM/page/subpage
How can I extract page/subpage this from the above string (in c#)?
If you are working with URL's you can use Uri class:
var url = new Uri("http://TEST.COM/");
var path = url.MakeRelativeUri(new Uri("http://TEST.COM/page/subpage"));
You can use split() :
// The directory
string dir = "http://TEST.COM/page/subpage";
// Split on directory separator
string[] parts = dir.Split('/');
And you will have an array. You can do with it what you want. And Split() string as you wish.
There could be various ways:
As #Selman mentioned using Uri class:
var url = new Uri("http://TEST.COM/");
var path = url.MakeRelativeUri(new Uri("http://TEST.COM/page/subpage"));
using IndexOf
var offset = myString.IndexOf('/');
offset = myString.IndexOf('/', offset+1);
var result = myString.IndexOf('/', offset+1);

Extracting text from ftp address

I'm creating small FTP Client and stuck on small issue, can you help me to sort it out please.
So I'm taking text from comboBox1.Text witch is lets say "/test/sql/it/"
But for creating new directory I need to extract "it" and "/test/sql/"
"it" as new directory name and "/test/sql/" location for creating new folder.
For second part I can use:
string s = comboBox1.Text;
s = s.Remove(s.LastIndexOf('/'));
s = s.Remove(s.LastIndexOf('/'));
s = s + "/";
MessageBox.Show(s);
//result "/test/sql/"
But how to get first part "it" any one?
try this,
string s = comboBox1.Text;
string path_s = Path.GetFileName( Path.GetDirectoryName( path ) );
The inner call to GetDirectoryName will return the full path, while the outer call to GetFileName() will return the last path component - which will be the folder name.
Try this:
string path = "/test/sql/it/";
string[] directories = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string lastDir = directories.Last();
Use this regex:
.+(/.+/)$
That will give you /it/in group 1.
If you don't want the slashes, use this regex instead:
.+/(.+)/$

Splitting strings with slashes in C#

I have the following types of strings. One with three slashes and one with two:
a) filepath = "/F00C/Home/About"
b) filepath = "/Administration/Menus"
What I need to do is a function that will allow me to get the values of "home" and "administration" and put into topMenu variable and get the values of "Menus" and "About" and put this into the subMenu variable.
I am familiar with the function slashes = filePath.Split('/'); but my situation is not so simple as there are the two types of variables and in both cases I just need to get the last two words.
Is there a simple way that I could make the Split function work for both without anything to complex?
What's wrong with something like this ?
var splits = filePath.Split('/');
var secondLast = splits[splits.Length-2];
var last = splits[splits.Length-1];
Remarks:
Any check on the length of splits array (that must be >= 2) is missing.
Also, this code works only with forward-slash ('/'). To support both backslash and forward-slash separators, have a look at #Saeed's answer
Am I'm missing something or you just want:
var split = filepath.Split('/');
var last = split[split.Length -1];
var prev = split[split.Length -2];
var items = filePath.Split('/');
first = items[items.Length - 2];
second = items[items.Length - 1];
Also if this is a actual path you can use Path:
var dir = Path.GetDirectoryName(filePath);
dir = Path.GetFileName(dir);
var file = Path.GetFileName(filePath);
Edit: I edited Path version as the way discussed my digEmAll.

How to cut a string

I have a strings like
"/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben"
And I need only "175_Jahre_STAEDTLER_Faszination_Schreiben" where "root" is separator. How can I do this?
"/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben".Split("/root/")[1] should give you "175_Jahre_STAEDTLER_Faszination_Schreiben"
Another method:
String newstring = file_path.Substring(file_path.LastIndexOf('/') + 1);
Check out the System.IO.Path methods - not quite files and folders but with the / delimiter it just might work!
If you're looking to extract a part of a string based on an overall pattern, regular expressions can be a good alternative in some situations.
string s = "/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben";
Regex re = new Regex(#"/root/(?<goodPart>\w+)$");
Match m = re.Match(s);
if (m.Success) {
return m.Groups["goodPart"].ToString();
}
string s = "/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben";
string separator = "root";
string slash = "/";
int idx = s.IndexOf(separator);
string result = s.SubString(idx + separator.Length + slash.Length);
Use String.Split to separate the string with "root" as the separator. Then use the second element of the resulting array.
If you need to find a relative path based on a base path (which it sounds like what the problem you are trying to solve is, or at least a generalization of your problem) you can use the System.Uri class. It does have it's limitations, however. The cleanest and most correct way to find a relative path is to use DirectoryInfo. With DirectoryInfo you can "walk" the directory tree (backwards or forwards) and build a hierarchy based on that. Then just do a little set manipulation to filter out duplicates and what you have left is your relative path. There are some details, like adding ellipses in the correct place, etc..., but DirectoryInfo is a good place to start in order to parse paths based on the current OS platform.
FYI - I just finished writing a component here at work to do just that so it's fairly fresh in my mind.
string s = "/LM/W3SVC/1216172363/root/175_Jahre_STAEDTLER_Faszination_Schreiben";
int li = s.LastIndexOf("root/");
s = s.Substring(li + 5, s.Length - 1 - (li + 4));
MessageBox.Show(s);

Categories

Resources