Given an absolute URI/URL, I want to get a URI/URL which doesn't contain the leaf portion. For example: given http://foo.com/bar/baz.html, I should get http://foo.com/bar/.
The code which I could come up with seems a bit lengthy, so I'm wondering if there is a better way.
static string GetParentUriString(Uri uri)
{
StringBuilder parentName = new StringBuilder();
// Append the scheme: http, ftp etc.
parentName.Append(uri.Scheme);
// Appned the '://' after the http, ftp etc.
parentName.Append("://");
// Append the host name www.foo.com
parentName.Append(uri.Host);
// Append each segment except the last one. The last one is the
// leaf and we will ignore it.
for (int i = 0; i < uri.Segments.Length - 1; i++)
{
parentName.Append(uri.Segments[i]);
}
return parentName.ToString();
}
One would use the function something like this:
static void Main(string[] args)
{
Uri uri = new Uri("http://foo.com/bar/baz.html");
// Should return http://foo.com/bar/
string parentName = GetParentUriString(uri);
}
Thanks,
Rohit
Did you try this? Seems simple enough.
Uri parent = new Uri(uri, "..");
This is the shortest I can come up with:
static string GetParentUriString(Uri uri)
{
return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length);
}
If you want to use the Last() method, you will have to include System.Linq.
There must be an easier way to do this with the built in uri methods but here is my twist on #unknown (yahoo)'s suggestion.
In this version you don't need System.Linq and it also handles URIs with query strings:
private static string GetParentUriString(Uri uri)
{
return uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments[uri.Segments.Length -1].Length - uri.Query.Length);
}
Quick and dirty
int pos = uriString.LastIndexOf('/');
if (pos > 0) { uriString = uriString.Substring(0, pos); }
Shortest way I found:
static Uri GetParent(Uri uri) {
return new Uri(uri, Path.GetDirectoryName(uri.LocalPath) + "/");
}
PapyRef's answer is incorrect, UriPartial.Path includes the filename.
new Uri(uri, ".").ToString()
seems to be cleanest/simplest implementation of the function requested.
I read many answers here but didn't find one that I liked because they break in some cases.
So, I am using this:
public Uri GetParentUri(Uri uri) {
var withoutQuery = new Uri(uri.GetComponents(UriComponents.Scheme |
UriComponents.UserInfo |
UriComponents.Host |
UriComponents.Port |
UriComponents.Path, UriFormat.UriEscaped));
var trimmed = new Uri(withoutQuery.AbsoluteUri.TrimEnd('/'));
var result = new Uri(trimmed, ".");
return result;
}
Note: It removes the Query and the Fragment intentionally.
new Uri(uri.AbsoluteUri + "/../")
Get segmenation of url
url="http://localhost:9572/School/Common/Admin/Default.aspx"
Dim name() As String = HttpContext.Current.Request.Url.Segments
now simply using for loop or by index, get parent directory name
code = name(2).Remove(name(2).IndexOf("/"))
This returns me, "Common"
Thought I'd chime in; despite it being almost 10 years, with the advent of the cloud, getting the parent Uri is a fairly common (and IMO more valuable) scenario, so combining some of the answers here you would simply use (extended) Uri semantics:
public static Uri Parent(this Uri uri)
{
return new Uri(uri.AbsoluteUri.Remove(uri.AbsoluteUri.Length - uri.Segments.Last().Length - uri.Query.Length).TrimEnd('/'));
}
var source = new Uri("https://foo.azure.com/bar/source/baz.html?q=1");
var parent = source.Parent(); // https://foo.azure.com/bar/source
var folder = parent.Segments.Last(); // source
I can't say I've tested every scenario, so caution advised.
Related
guys i tried this one:
current: \netcoreapp2.1\ResultPath
target : \netcoreapp2.1\ReportPath\report1
AssemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Uri currentPath = new Uri(AssemblyDirectory + "//ResultPath");
Uri targetPath = new Uri(reportsSubDir);
Uri relPath = currentPath.MakeRelativeUri(targetPath);
In result i'm getting
relPath.OriginalString = ReportPath/report1
Why is not ../ReportPath/report1 ?
And now for example:
if i have
current: \netcoreapp2.1\ResultPath\Test
target : \netcoreapp2.1\ReportPath\report1
I'm getting correct result in this way
relPath.OriginalString = ../../ReportPath/report10
Could anyone explain me why in first step i'm getting bad Relative Path, but in second good
and any idea how can i fix it, if i want to use first and second examples in my way ?
Well, if you are using .NET 5, you're in luck, since new method was included: Path.GetRelativePath(string, string)
If not, we can always dig into MS .NET Framework code:
https://referencesource.microsoft.com/#System.Workflow.ComponentModel/AuthoringOM/Design/DesignerHelpers.cs,a561eb779ce7163d
And copy implementation, which is:
static class PathHelper
{
internal static string GetRelativePath(string pathFrom, string pathTo)
{
Uri uri = new Uri(pathFrom);
string relativePath = Uri.UnescapeDataString(uri.MakeRelativeUri(new Uri(pathTo)).ToString());
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
if (!relativePath.Contains(Path.DirectorySeparatorChar.ToString()))
relativePath = "." + Path.DirectorySeparatorChar + relativePath;
return relativePath;
}
}
Usage then would be:
var p1 = #"C:\users\turek\source\";
var p2 = #"C:\users\turek\desktop\";
PathHelper.GetRelativePath(p1, p2);
// returns "..\\desktop\\"
Found answer added / to current Path it looks like ::
Uri currentPath = new Uri(AssemblyDirectory + "//ResultPath/");
Still need explanation :)
I'm trying to make C# program that gets a line on a website and use it.
Unfortunately, I don't know the full line on the site. I only know "steam://joinlobby/730/". Although, what comes after "/730/" is always different.
So i need help getting the full line that comes after it.
What I've got:
public void Main()
{
WebClient web = new WebClient();
// here is the site that i want to download and read text from it.
string result = web.DownloadString("http://steamcommunity.com/id/peppahtank");
if (result.Contains("steam://joinlobby/730/"))
{
//get the part after /730/
}
}
I can tell you that it always ends with "xxxxxxxxxxxxxxxxx/xxxxxxxxxxxxxxxxxx"
so: steam://joinlobby/730/xxxxxxxxx/xxxxxxxx.
What's to prevent you from just splitting the string on '/730/'?
result.Split(#"/730/")[1]
https://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx
The easiest method for this particular case would be to take the first part, and then just skip that many characters
const string Prefix = #"steam://joinlobby/730/";
//...
if(result.StartsWith(Prefix))
{
var otherPart = result.SubString(Prefix.Length);
// TODO: Process other part
}
Make sure your result is not null and begins with steam://joinlobby/730/
if(string.IsNullOrWhiteSpaces(result) && result.StartsWith("steam://joinlobby/730/"))
{
string rest = result.SubString(("steam://joinlobby/730/").Length);
}
I had trouble downloading a file from Mediafire. I found out the I have to use their API. I found another SO question: "Get direct download link and file site from Mediafire.com"
With the help of the shown functions I created the following class:
class Program
{
static void Main(string[] args)
{
Mediafireclass mf = new Mediafireclass();
WebClient webClient = new WebClient();
mf.Mediafiredownload("somemediafirelink/test.txt");
webClient.DownloadFileAsync(new Uri("somemediafirelink/test.txt"), #"location to save/test.txt");
}
}
and used the function by T3KBAU5 like this:
internal class Mediafireclass
{
public string Mediafiredownload(string download)
{
HttpWebRequest req;
HttpWebResponse res;
string str = "";
req = (HttpWebRequest)WebRequest.Create(download);
res = (HttpWebResponse)req.GetResponse();
str = new StreamReader(res.GetResponseStream()).ReadToEnd();
int indexurl = str.IndexOf("http://download");
int indexend = GetNextIndexOf('"', str, indexurl);
string direct = str.Substring(indexurl, indexend - indexurl);
return direct;
}
private int GetNextIndexOf(char c, string source, int start)
{
if (start < 0 || start > source.Length - 1)
{
throw new ArgumentOutOfRangeException();
}
for (int i = start; i < source.Length; i++)
{
if (source[i] == c)
{
return i;
}
}
return -1;
}
}
But when I run it this error pops up:
Screenshot of the Error
What can I do to solve the problem, and can you explain what this error means?
Firstly, the Mediafiredownload method returns a string, the direct download link, which you are not using. Your code should resemble:
Mediafireclass mf = new Mediafireclass();
WebClient webClient = new WebClient();
string directLink = mf.Mediafiredownload("somemediafirelink/test.txt");
webClient.DownloadFileAsync(new Uri(directLink), #"location to save/test.txt");
As for the exception it's firing, it's important to understand what the GetNextIndexOf method is doing - iterating through a string, source, to find the index of a character, c, after a certain start position, start. The first line in that method is checking that the start value is within the length of the source string, so that it doesn't immediately look at a character out of the range and throw an ArgumentOutOfRangeException. You need to set a breakpoint on this line:
int indexend = GetNextIndexOf('"', str, indexurl);
And look at the values of str and indexurl using the locals window. This will reveal the problem.
Also, the code you are using is almost 5 years old and I expect this problem is more to do with the fact that Mediafire will have changed the URL structure since then. Your code relies on the fact that the url contains "http://download" which may not be the case any more.
The easiest way is to use an dll file. Such as DirektDownloadLinkCatcher.
Or u have to query for the right div by the "download_link" class and the get the href of the containing tag. Thats the way how I solved it in these dll.^^
Or use the API from MediaFire.
Hoped I could help.
In ASP.Net it is posible to get same content from almost equal pages by URLs like
localhost:9000/Index.aspx and localhost:9000//Index.aspx or even localhost:9000///Index.aspx
But it isn't looks good for me.
How can i remove this additional slashes before user go to some page and in what place?
Use this :
url = Regex.Replace(url , #"/+", #"/");
it will support n times
see
https://stackoverflow.com/a/19689870
https://msdn.microsoft.com/en-us/library/9hst1w91.aspx#Examples
You need to specify a base Uri and a relative path to get the canonized behavior.
Uri baseUri = new Uri("http://www.contoso.com");
Uri myUri = new Uri(baseUri, "catalog/shownew.htm");
Console.WriteLine(myUri.ToString());
This solution is not that pretty but very easy
do
{
url = url.Replace("//", "/");
}
while(url.Contains("//"));
This will work for many slashes in your url but the runtime is not that great.
Remove them, for example:
url = url.Replace("///", "/").Replace("//", "/");
Regex.Replace("http://localhost:3000///////asdasd/as///asdasda///asdasdasd//", #"/+", #"/").Replace(":/", "://")
Here is the code snippets for combining URL segments, with the ability of removing the duplicate slashes:
public class PathUtils
{
public static string UrlCombine(params string[] components)
{
var isUnixPath = Path.DirectorySeparatorChar == '/';
for (var i = 1; i < components.Length; i++)
{
if (Path.IsPathRooted(components[i])) components[i] = components[i].TrimStart('/', '\\');
}
var url = Path.Combine(components);
if (!isUnixPath)
{
url = url.Replace(Path.DirectorySeparatorChar, '/');
}
return Regex.Replace(url, #"(?<!(http:|https:))//", #"/");
}
}
I'm new to Ektron, and I'm having trouble finding decent documentation on how to get content. I have a folder that contains smartforms. In my code, I need to get all those smartforms. This is all I have so far:
var folderManager = new FolderManager();
var folder = folderManager.GetTree(Convert.ToInt64(ConfigurationManager.AppSettings["AlumniSlideshowFolderId"]));
But from there, I have no idea how to get my data. Please help!
Something like this should do the trick. You'll actually want to use the ContentManager instead of the FolderManager. The criteria object is pretty powerful... you can refine the list down further if you need to.
var contentManager = new ContentManager();
int recordsPerPage;
int.TryParse(ConfigurationManager.AppSettings["AlumniSlideshow.RecordsPerPage"], out recordsPerPage);
int currentPage;
int.TryParse(HttpContext.Current.Request.QueryString["p"], out currentPage);
if (currentPage <= 0)
{
currentPage = 1;
}
long alumniSlideshowFolderId;
long.TryParse(ConfigurationManager.AppSettings["AlumniSlideshowFolderId"], out alumniSlideshowFolderId);
var criteria = new ContentCriteria();
criteria.AddFilter(ContentProperty.FolderId, CriteriaFilterOperator.EqualTo, alumniSlideshowFolderId);
// By default, the GetList method will use a 'recordsPerPage' value of 50.
criteria.PagingInfo = new PagingInfo(recordsPerPage, currentPage);
var content = contentManager.GetList(criteria);
foreach (var contentData in content)
{
// work with each result here
}
You also mentioned not finding good documentation. Here are a few links. There is some pretty good documentation available, especially for the newer FrameworkAPI classes. You just have to know where to look.
http://documentation.ektron.com/cms400/edr/web/edr.htm
http://documentation.ektron.com/cms400/edr/web/Content/FrameworkAPI/Content/ContentManager.htm