C# Remove URL from String - c#

This seems like a really easy one but everything I try doesn't seem to work
say I have the following string:
string myString = "http://www.mysite.com/folder/file.jpg";
How can I process that to remove the URL and just leave "file.jpg" as the string value?
Thanks!
Kris

You can always use System.IO.Path methods
string myString = "http://www.mysite.com/folder/file.jpg";
string fileName = Path.GetFileName(myString); // file.jpg
If you do want to process more complex URIs you can pass it thought the System.Uri type and grab the AbsolutePath
string myString = "http://www.mysite.com/folder/file.jpg?test=1";
Uri uri = new Uri(myString);
string file = Path.GetFileName(uri.AbsolutePath);

string lastPart = myString.Substring(myString.LastIndexOf('/') + 1);

Related

Splitting the string by few delimeter

I have a string with me and I want to call a rest method from that string. Can anyone think of a better approach then the one I described below for converting str to Rest Call Url.
str : https://P1.P2.com/ProjectName/_build?definitionId=123
Extract P1 and ProjectName and definitionId
Rest Call : https://dev.azure.com/P1/ProjectName/_apis/pipelines/123/runs?api-version=6.0-preview.1
Here, after getting the string, split it with "//" and then split array[1] with "/" and then get P1, ProjectName and then find something with "=" and then the number ?
Not sure if this might be ok.
Update :
I can get this as a URI. But how to convert it then ?
First off, use Uri to parse out the host, path, and query parts of the URI:
var uri = new Uri("https://P1.P2.com/ProjectName/_build?definitionId=123");
For extracting P1 from the host, it's probably going to be easiest to split on .:
string subdomain = uri.Host.Split('.')[0]
For ProjectName, just look at uri.Segments:
string projectName = uri.Segments[1];
For definitionId, parse the query string with HttpUtility.ParseQueryString:
var query = HttpUtility.ParseQueryString(uri.Query);
string definitionId = query["definitionId"];
To construct the new Uri, use a UriBuilder:
var builder = new UriBuilder()
{
Scheme = "https",
Host = "dev.azure.com",
Path = $"{subdomain}/{projectName}_apis/pipelines/{definitionId}/runs",
Query = "api-version=6.0-preview.1",
};
string result = builder.ToString();
See it on dotnetfiddle.net

How to delete string from another string position in c#

I have two string:
string url = HttpContext.Current.Request.Url.AbsoluteUri;
//give me :
//url = http://localhost:1302/TESTERS/Default6.aspx?tabindex=2&tabid=15
And:
string path = HttpContext.Current.Request.Url.AbsolutePath;
//give me:
//path = /TESTERS/Default6.aspx
Now I want to get the string:
http://localhost:1302
So what I am thinking of is I will find the position of path in url and remove the sub-string from this position in url.
What I tried:
string strApp = url.Remove(url.First(path));
or
string strApp = url.Remove(url.find_first_of(path));
but I can't find the write way to express this idea. How can I archive my goal?
So basically you want the URL, from the start up to the beginning of your path.
You don't need to "remove" that part, only take characters up to that precise point. First, you can get that location with a simple IndexOf as it returns the position of the first character that matches your string. After this, simply take the part of url that goes from 0 to that index with Substring.
string url = "http://localhost:1302/TESTERS/Default6.aspx?tabindex=2&tabid=15";
string path = "/TESTERS/Default6.aspx";
int indexOfPath = url.IndexOf(path);
string strApp = url.Substring(0, indexOfPath); // gives http://localhost:1302
Which you can shorten to
string strApp = url.Substring(0, url.IndexOf(path));
you can also do something like below code to get the Host of URI
Uri uri =HttpContext.Current.Request.Url.AbsoluteUri ;
string host = uri.Authority; // "example.com"
Here is another option.. this doesn't require any string manipulation:
new Uri(HttpContext.Current.Request.Url, "/").AbsoluteUri
It generates a new Uri which is the path "/" relative to the original Url
You should just use this instead:
string baseURL = HttpContext.Current.Context.Request.Url.Scheme + "://" +
HttpContext.Current.Context.Request.Url.Authority;
This should not be solved using string manipulation. HttpContext.Current.Request.Url returns an Uri object which has capabilities to return the information you request.
var requestUrl = HttpContext.Current.Request.Url;
var result = requestUrl.GetComponents(UriComponents.SchemeAndServer,
UriFormat.Unescaped);
// result = "http://localhost:1302"

C# how to add parameters to a string with braces at the beginning?

I have the next string:
public const string BaseAddress = "http://test.i-swarm.com/i-swarm/api/v1/";
public const string LoginURL = "{0}sessions";
I want to make a url of LoginURL where the {0} is the BaseAddress.
The logical way is not working:
string str = string.Format(BaseAddress, LoginURL);
It only prints the BaseAddress.
It will work if I do this:
string str = string.Format(LoginURL, BaseAddress); //Is this the correct way?
It's not logical way, you are defining parameter in LoginUrl not in BaseAddress, so it's working correctly
If you want it work logicaly do it that way:
public const string BaseAddress = "http://test.i-swarm.com/i-swarm/api/v1/{0}";
public const string LoginURL = "sessions";
string.Format is replacing {0} with first parameter, so it will now work like you want it to work.
string str = string.Format(LoginURL, BaseAddress); //Is this the correct way?
Yes, that is the correct way. Although it doesn't follow the usual pattern people use. Please read the documentation for the function located here: http://msdn.microsoft.com/en-us/library/system.string.format.aspx
The first argument is the Format, the second are the arguments/replacement values. Assuming you want to maintain a constant format, that is usually a hardcoded in the argument as such:
string str = string.Format("{0}sessions", BaseAddress);
Being as it seems the base address is normally more consistent (but may still be variable) an approach such as the following may be better:
public const string BaseAddress = "http://test.i-swarm.com/i-swarm/api/v1/";
public const string LoginURL = "sessions";
string str = string.Format("{0}{1}", BaseAddress, LoginURL);
If your end-goal is just URL combination rather than an exercise using string.Format, the following may still be a better approach:
Uri baseUri = new Uri("http://test.i-swarm.com/i-swarm/api/v1/");
Uri myUri = new Uri(baseUri, "sessions");
That way you don't have to worry about whether or not a separator was used in the base address/relative address/etc.
There is no logical way, there's just one way to comply to how String.Format works. String.Format is defined so that the first parameter contains the string into which parameters will be inserted, then follows a list of the parameters.
If you define the strings like you do, the only correct way is
string str = string.Format(LoginURL, BaseAddress);
It would be more intuitive, however, if the BaseAddress was the format string:
public const string BaseAddress = "http://test.i-swarm.com/i-swarm/api/v1/{0}";
public const string LoginURL = "sessions";
So you could write
string str = String.Format(BaseAddress, LoginURL);
Yes the correct way is:
string str = String.Format(LoginURL, BaseAddress);
The format string should always be the first parameter.
Though I feel that:
string str = String.Format("{0}sessions", BaseAddress);
Is more readable.
You can use C#'s interpolated strings.
string BaseAddress = "http://test.i-swarm.com/i-swarm/api/v1/";
string LoginURL = $"{BaseAddress}sessions";
You can have multiple parameters. This is a safer method of formatting strings as when using string.Format you need to make sure that order of parameters are correct. With this new way you don't have to.
string foo = "foo";
int bar = 4;
string result = $"{bar} hello {foo}";
Reference:
What's with the dollar sign ($"string")
MSDN - Interpolated Strings

How to remove characters in a string?

How to remove the some characters in a string ..
string s="testpage\information.xml"
I need only information.xml how to do that?
System.IO.Path may help you with this since the string contains a file path information. In your case, you may use Path.GetFileName(string path) to get the file name from a string.
Example
string s = #"testpage\information.xml";
string filename = Path.GetFileName(s);
//MessageBox.Show(filename);
Thanks,
I hope you find this helpful :)
Assuming the value that will be in s is always a file path, use the Path class to extract the file name
var filename = Path.GetFileName(s);
File path is of the form
aaaa\bbb\ccc\dddd\information.xml
To retrieve the last string, you can divide your string using the delimiter \
String path = #"aaaa\bbb\ccc\dddd\information.xml";
String a[] = path.Split('\\');
This will give String array as ["aaaa", "bbb", "ccc", "dddd", "information.xml"]
You can retrieve the filename as
String filename = a[a.Length-1];
If it is going to be a file path, then you can use the System.IO.Path class (MSDN) to extract the filename.
string s = "testpage\information.xml"
var filename = Path.GetFilename(s);
If it's always right of the backslash separator then you can use:
if (s.Contains(#"\"))
s= s.Substring(s.IndexOf(#"\") + 1);
Hope this is what you want:
var result=s.Substring(s.LastIndexOf(#"\") + 1);
If you are using file paths, see the Path.GetFileName Method
It will not check whether the file exists or not. So it will be faster.
s = Path.GetFileName(s);
If you need to check whether file exists, use File.Exists class.
Another way is to use String.Split() method
string[] arr = s.Split('\\');
if(arr.Length > 0)
{
s = arr[arr.Length - 1];
}
Another way is to use RegEx
s = Regex.Match(s, #"[^\\]*$").Value;
You can use the following line of codes to get file extension.
string filePath = #"D:\Test\information.xml";
string extention = Path.GetExtension(filePath);
If you need file name alone use,
string filePath = #"D:\Test\information.xml";
string filename = Path.GetFilename(filePath );
Use string.Replcae
string s = #"testpage\information.xml";
s = s.Replace(#"testpage\\",""); // replace 'testpage\' with empty string
You will get Output => s=information.xml
# is need only because you have backslash in your string
For further reading about STRING REPLACE
http://www.dotnetperls.com/replace
http://msdn.microsoft.com/en-us/library/system.string.replace.aspx
In C++ you can do something like this. Basically search for "/" or "\" from right to left of the path and crop the string starting from the first occurance of the delimiter:
string ExtractFileName(const string& strPathFileName)
{
size_t npos;
string strOutput = strPathFileName;
if(strPathFileName.rfind(L'/', npos) || strPathFileName.rfind(L'\\', npos))
{
strOutput = strPathFileName.substr(npos+1);
}
return strOutput;
}

How to split string based on another string

I have a string:
string fileName = VAH007157100_REINSTMT_20d5fe49.tiff
I want to split this at the end of REINSTMT.
string splittedFileName = fileName.split("REINSTMT")[0];
The above does not work.
How would I go about splitting it to grab everything from the left side of the word "REINSTMT"?
Try this
string splittedFileName = fileName.Split(new string[]{"REINSTMT"},
StringSplitOptions.None)[0];
In order to split based on a string rather than a char, you need to provide a second argument. See the documentation here.
What you probably want is
string splittedFileName = fileName.split(new string[] {"REINSTMT"}, StringSplitOptions.None)[0];
Another way would be with substring:
string fileName = "VAH007157100_REINSTMT_20d5fe49.tiff";
string splittedFileName = fileName.Substring(0, fileName.IndexOf("REINSTMT"));

Categories

Resources