Trim machine name from Hostinfo - c#

I want to trim the machine name from my Hostname so that I can get the server name.
But I'm not able to figure out how.
This is my code:
string machineName = System.Environment.MachineName;
hostinfo = Dns.GetHostEntry(str); //Fetches the name of the system in the Network (SystemName.canon.co.in)
string Original = hostinfo.HostName.ToString();
Now the string contains the data like:
MachineName.ServerName
blah.comp.co.uk
So I want to remove blah. from the string so that what I am left with is comp.co.uk.
Can anyone help me out with it?

try this
string Original = "blah.comp.co.uk";
string[] ss = Original.Split(".".ToCharArray(), 2);
string Result = ss[1];
EDIT:
string Original = "blah.comp.co.uk";
string[] ss = Original.Split(new[] {'.'}, 2);
string Result = ss[1];

Related

Dealing with multiple '.' in a file extension

I have this string that contains a filename
string filename = "C:\\Users\\me\\Desktop\\filename.This.Is.An.Extension"
I tried using the conventional
string modifiedFileName = System.IO.Path.GetFileNameWithoutExtension(filename);
but it only gets me:
modifiedFileName = "C:\\Users\\me\\Desktop\\filename.This.Is.An"
In order for me to get "C:\\Users\\me\\Desktop\\filename" I would have to use System.IO.Path.GetFileNameWithoutExtension several times, and that's just not efficient.
What better way is there to take my file name and have it return the directory + filename and no exceptions?
Many thanks in advance!
If you want to stop at the first period, you will have to handle it yourself.
Path.GetDirectoryName(filepath) + Path.GetFileName(filepath).UpTo(".")
using this string extension:
public static string UpTo(this string s, string stopper) => s.Substring(0, Math.Max(0, s.IndexOf(stopper)));
Take the directory and the base name:
var directoryPath = Path.GetDirectoryName(filename);
var baseName = Path.GetFileName(filename);
Strip the base name’s “extensions”:
var baseNameWithoutExtensions = baseName.Split(new[] {'.'}, 2)[0];
Recombine them:
var modifiedFileName = Path.Combine(directoryPath, baseNameWithoutExtensions);
demo
Without built in function:
public static void Main(string[] args)
{
string s = "C:\\Users\\me\\Desktop\\filename.This.Is.An.Extension";
string newString="";
for(int i=0;i<s.Length;i++)
{
if(s[i]=='.'){
break;
}else{
newString += s[i].ToString();
}
}
Console.WriteLine(newString); //writes "C:\Users\me\Desktop\filename"
}

HttpContext.Current.Request.Url How to get the part after application name from URL

var myPath = HttpContext.Current.Request.Url.AbsolutePath;
// output: myApplication/myFolder/myPage.aspx
var pageName = Path.GetFileName(myPath);
//output: myPage.aspx
I am trying to output "myFolder/myPage.aspx" without the application path.
Is there built-in option to return that or I would need to use regular expression to get what I need?
Thanks
You should be able to make use of HttpContext.Current.Request.Url.Segments and then a simple string concat:
String[] segments = HttpContext.Current.Request.Url.Segments;
string result = segments[1] + segments[2];
or instead of string concat, use: string result = Path.Combine(segments[1],segments[2]);
This should work
public ActionResult oihoi(string ImageName
{
string _FileName = Path.GetFileName(ImageName.FileName);
string folderpath = "UploadedFiles/WebGallery";
string path = Server.MapPath("~/" + folderpath);
string firstsegment = "";
}

Extract name and surname from string in c#

I need extract the name and surname from a email string.
In the database I have two type of address email working :
name.surname#xxxx.eu
Or
name.surname#xxxx.com
And I have tried this code :
string Email1 = Email.ToString().ToUpper().Replace("#", "");
if (Email1.Contains("XXXX.COM"))
{
Response.Write(Email1.ToString().Replace(".", " ").ToUpper().Remove(Email1.Length - 8, 8) + "<br />");
}
else
{
Response.Write(Email1.ToString().Replace(".", " ").ToUpper().Remove(Email1.Length - 7, 7) + "<br />");
}
This code not working for only these addresses emails :
VINCENT.NAPOLITAIN#XXXX.EU
because the return is :
VINCENT NAPOLITAINX
Not working for :
MARK.CHAIN#XXXX.COM
because the return is :
MARK CHAINX
Not working for :
NICODEMUS.ANGELICUM#XXXX.EU
because the return is :
NICODEMUS ANGELICUMX
How to do resolve this?
Please help me, thank you so much in advance.
why don't you split your address by the both seperator characters # and .
string email = "VINCENT.NAPOLITAIN#XXXX.EU";
string[] result = email.Split('.', '#').ToArray();
string firstname = result[0];
string lastname = result[1];
Simplistic approach (based on the requirements that you specified, which seem to be a bit strange):
var test = "name.surname#xxxx.eu";
var name = test.Substring(0, test.IndexOf('#')).Replace(".", " ");
Might want to add exception handling, of course.
You can use String.split():
string email = "VINCENT.NAPOLITAIN#XXXX.EU";
string names = email.Split('#')[0];
string name = "";
string surname = "";
if (names.Contains('.'))
{
var nameSurname = names.Split('.');
name = nameSurname[0]; //
surname = nameSurname[1];
}
You can use Regex Pattern:
(.+)\.(.+)(?=\#)
Explanation:
(.+) - Matches any character in a group
\. - Matches (.) dot
(?=\#) - Exclude # character
Code:
var match = Regex.Match(email, pattern);
var name = match.Groups[1].Value;
var surname = match.Groups[2].Value;
One option is to find the index of the . and the index of the # and do substrings on that:
string email = "aa.bb#cc.dd";
int periodIndex = email.IndexOf('.');
int atIndex = email.IndexOf('#');
string firstName = email.Substring(0, periodIndex);
string lastName = email.Substring(periodIndex + 1, atIndex - periodIndex - 1);
An easier way is to use a regular expression that cuts out the names.
This one will do:
(.*?)\.(.*?)#(.*)
The first capture is the first name, the second capture is the last name.
I would just use split in order to do it:
var nameDOTsurname = Email1.Split('#'); // This would leave in nameDOTsurname[0] the name.surname and in nameDOTsurname[1] the XXX.whatever
var name = nameDOTsurname[0].Split('.')[0];
var surname = nameDOTsurname[0].Split('.')[1];
This will work if your email address format sticks to firstname.secondname#wherever...
here is the code that works for you...
string e = "VINCENT.NAPOLITAIN#XXXX.EU";
string firstname = e.Substring(0, e.IndexOf("."));
string secondname = s.Substring(s.IndexOf(".")+1, s.IndexOf("#")-s.IndexOf(".")-1);
It works for all your emails

How to extract a string from a string in c#

VS 2015, c#.
I have a string...
string str = "Name;IPAddress";
I want to extract just the IPAddress.
I suspect Regex is the best way to do it but I am unsure.
Any assistance greatly appreciated.
You can use Split
string str = "Name;IPAddress";
string[] both = str.Split(';');
string name = both[0];
string ipadd = both[1];
Why do you think Regex is the best way? Do you also want to validate name and IP address?
string sInput = "John;127.0.0.1";
string[] arrNameAndIP = sInput.Split(';');
bool bIsInputValid = false;
if(arrNameAndIP.Length == 2)
{
Regex rgxNamePattern = new Regex("^[A-za-z]+$");
bool bIsNameValid = rgxNamePattern.IsMatch(arrNameAndIP[0]);
IPAddress ipAddress;
bool bIsIPValid = IPAddress.TryParse(arrNameAndIP[1], out ipAddress);
bIsInputValid = bIsNameValid && bIsIPValid;
}

Grab a part of text when it matches, get rid of the rest because it's useless

I have a text called
string path = "Default/abc/cde/css/";
I want to compare a text.
string compare = "abc";
I want a result
string result = "Default/abc";
The rest of the path /cde/css is useless.Is it possible to grab the desire result in asp.net c#. Thanks.
Is this what you looking for?:
string result = path.Substring(0, path.IndexOf(compare)+compare.Length);
Try this. This will loop through the different levels (assuming these are directory levels) until it matches the compare, and then exit the loop. This means that if there is a folder called abcd, this won't end the loop.
string path = "Default/abc/cde/css";
string compare = "abc";
string result = string.Empty;
foreach (string lvl in path.Split("/")) {
result += lvl + "/";
if (lvl == compare)
{
break;
}
}
if (result.Length>0)
{
result = result.substring(0, result.length-1);
}
string path = "Default/abc/cde/css/";
string answer = "";
string compare = "abc";
if (path.Contains(compare ))
{
answer = path.Substring(0, path.IndexOf(stringToMatch) + compare.Length);
}
Something like the above should work.
I suggest that if you meet questions of this kind in the future, you should try it yourself first.
string result = path.Contains(compare) ? path.Substring(0, (path.IndexOf(compare) + compare.Length)) : path;

Categories