Validate folder name in C# - c#

I need to validate a folder name in c#.
I have tried the following regex :
^(.*?/|.*?\\)?([^\./|^\.\\]+)(?:\.([^\\]*)|)$
but it fails and I also tried using GetInvalidPathChars().
It fails when i try using P:\abc as a folder name i.e Driveletter:\foldername
Can anyone suggest why?

You could do that in this way (using System.IO.Path.InvalidPathChars constant):
bool IsValidFilename(string testName)
{
Regex containsABadCharacter = new Regex("[" + Regex.Escape(System.IO.Path.InvalidPathChars) + "]");
if (containsABadCharacter.IsMatch(testName) { return false; };
// other checks for UNC, drive-path format, etc
return true;
}
[edit]
If you want a regular expression that validates a folder path, then you could use this one:
Regex regex = new Regex("^([a-zA-Z]:)?(\\\\[^<>:\"/\\\\|?*]+)+\\\\?$");
[edit 2]
I've remembered one tricky thing that lets you check if the path is correct:
var invalidPathChars = Path.GetInvalidPathChars(path)
or (for files):
var invalidFileNameChars = Path.GetInvalidFileNameChars(fileName)

Validating a folder name correctly can be quite a mission. See my blog post Taking data binding, validation and MVVM to the next level - part 2.
Don't be fooled by the title, it's about validating file system paths, and it illustrates some of the complexities involved in using the methods provided in the .Net framework. While you may want to use a regex, it isn't the most reliable way to do the job.

this is regex you should use :
Regex regex = new Regex("^([a-zA-Z0-9][^*/><?\"|:]*)$");
if (!regex.IsMatch(txtFolderName.Text))
{
MessageBox.Show(this, "Folder fail", "info", MessageBoxButtons.OK, MessageBoxIcon.Information);
metrotxtFolderName.Focus();
}

Related

Determine if a given url (from a string) is from my domain or not

I'm trying to check from c# code if a given url is from my domain or not, in order to add the "nofollow" and "target _Blank" attributes for external links.
When i talk about external links i refer to any link outside my domain.
By default it does not have that attributes. I tried a lot of stuff, basically this is the part i need to fix:
public void PrepareLink(HtmlTag tag)
{
string url = tag.attributes["href"];
if (PrepareLink != null)
{
if (it is from an external site???)
{
tag.attributes["rel"] = "nofollow";
tag.attributes["target"] = "_blank";
}
}
Edit:
things i've tried:
string dominioLink = new Uri(url).Host.ToLower();
if (!dominioLink.Contains(myDomainURL))
{
tag.attributes["rel"] = "nofollow";
tag.attributes["target"] = "_blank";
}
Which has the issue that dont take in mind subdomains
i.e. if a link created is http://www.mydomain.com.anotherfakedomain.com, it will return true and work well.
I've looked in every Uri property but didn't seem to contains the base domain.
I'm currently using .NET Core 2.0.
thankS! please if you need any other data just let me know.
You can use the Uri.Host property to obtain the domain from a URL string, then compare it to your own. I suggest using a case-insensitive match.
var url = tag.attributes["href"];
var uri = new Uri(url);
var match = uri.Host.Equals(myDomain, StringComparison.InvariantCultureIgnoreCase)

Using Regex to insert domain name into url

I am pulling in text from a database that is formatted like the sample below. I want to insert the domain name in front of every URL within this block of text.
<p>We recommend you check out the article
<a id="navitem" href="/article/why-apples-new-iphones-may-delight-and-worry-it-pros/" target="_top">
Why Apple's new iPhones may delight and worry IT pros</a> to learn more</p>
So with the example above in mind I want to insert http://www.mydomainname.com/ into the URL so it reads:
href="http://www.mydomainname.com/article/why-apples-new-iphones-may-delight-and-worry-it-pros/"
I figured I could use regex and replace href=" with href="http://www.mydomainname.com but this appears to not be working as I intended. Any suggestions or better methods I should be attempting?
var content = Regex.Replace(DataBinder.Eval(e.Item.DataItem, "Content").ToString(),
"^href=\"$", "href=\"https://www.mydomainname.com/");
You could use regex...
...but it's very much the wrong tool for the job.
Uri has some handy constructors/factory methods for just this purpose:
Uri ConvertHref(Uri sourcePageUri, string href)
{
//could really just be return new Uri(sourcePageUri, href);
//but TryCreate gives more options...
Uri newAbsUri;
if (Uri.TryCreate(sourcePageUri, href, out newAbsUri))
{
return newAbsUri;
}
throw new Exception();
}
so, say sourcePageUri is
var sourcePageUri = new Uri("https://somehost/some/page");
the output of our method with a few different values for href:
https://www.foo.com/woo/har => https://www.foo.com/woo/har
/woo/har => https://somehost/woo/har
woo/har => https://somehost/some/woo/har
...so it's the same interpretation as the browser makes. Perfect, no?
Try this code:
var content = Regex.Replace(DataBinder.Eval(e.Item.DataItem, "Content").ToString(),
"(href=[ \t]*\")\/", "$1https://www.mydomainname.com/", RegexOptions.Multiline);
Use html parser, like CsQuery.
var html = "your html text here";
var path = "http://www.mydomainname.com";
CQ dom = html;
CQ links = dom["a"];
foreach (var link in links)
link.SetAttribute("href", path + link["href"]);
html = dom.Html();

Can't modify spotify playlist

I am using JohnnyCrazy/SpotifyAPI-NET for this application in Visual Studio.
The code creates a playlist just fine, but I can't modify it in any way(adding tracks, making the playlist private/public).
I am using the right scope (Scope.PlaylistModifyPrivate | Scope.PlaylistModifyPublic)
private FullPlaylist currentPlaylist;
public void DoThisStuff()
{
_profile = _spotify.GetPrivateProfile();
currentPlaylist = _spotify.CreatePlaylist(_profile.Id, Convert.ToString(DateTime.Now), false);
_spotify.AddPlaylistTrack(_profile.Id, currentPlaylist.Uri, "41VtJHghmomTfNrbTSF2Uj");
}
ok I found the solution:
currentPlaylist.Uri
That code gives me this: spotify:user:myname:playlist:02DfsHuBWwi1aCp8kxwVrs
but what I need is just the id at the end, so I cut it with
currentPlaylist.Uri.Substring(30)
An imperfect solution, as it will cause errors when the username has a different length than 7, but it works for now.
This solution is slightly less imperfect than the one you came up with.
currentPlaylist.Uri.Split(new[] {":playlist:"}, StringSplitOptions.None)[1]);
string playListUri = playlist.Uri.Substring(playlist.Uri.LastIndexOf(":") + 1);
Clean way to get URI from the string.
spotify:user:myname:playlist:02DfsHuBWwi1aCp8kxwVrs is separated by : so that you can split the string in multiple sub-strings. You then select the string you are interested in like so:
currentPlaylist.Uri.Split(':')[4] // Returns 02DfsHuBWwi1aCp8kxwVrs

C# check if a string is a valid WebProxy format

so after searching both on here and Google I have been unable to find a solution. Basically I want to allow the user to add a list of proxies from a text file, but I want to check that what gets passed in is a valid Proxy format before I make the WebProxy. I know using try catch like try {var proxy = new WebProxy(host + ":" + port;} catch{} will work, but as you may already know using try catch is slow, even more so when doing it in bulk.
So what would be a good and fast way to test a string to see if it's in a valid WebProxy format?
Thanks
This is how I do it:
var ValidIpAddressPortRegex = #"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]):[\d]+$";
if (System.Text.RegularExpressions.Regex.IsMatch(proxy_string_to_validate, ValidIpAddressPortRegex ))
{
do_stuff_with_proxy();
}
else
{
//MessageBox.Show("IP:PORT url not valid!","Information");
}

Check if input in textbox is email

I am trying to validate if the userinput is an email adress (adding a member to database).
The user will enter data in TextBox, when the validating event gets called; I want to check if the input is a valid email adress. So consisting of atleast an # and a dot(.) in the string.
Is there any way to do this through code, or perhaps with a Mask from the MaskedTextbox?
Don't bother with Regex. It's a Bad Idea.
I normally never use exceptions to control flow in the program, but personally, in this instance, I prefer to let the experts who created the MailAddress class do the work for me:
try
{
var test = new MailAddress("");
}
catch (FormatException ex)
{
// wrong format for email
}
Do not use a regular expression, it misses so many cases it's not even funny, and besides smarter people that us have come before to solve this problem.
using System.ComponentModel.DataAnnotations;
public class TestModel{
[EmailAddress]
public string Email { get; set; }
}
Regex for simple email match:
#"\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b"
Regex for RFC 2822 standard email match:
#"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
See: How to: Verify that Strings Are in Valid Email Format - MSDN
The Regex you are looking should be:
"^(?("")(""[^""]+?""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))
(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,24}))$"
(From the same source)
I recommend you use this way and it's working well for me.
Regex reg = new Regex(#"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*");
if (!reg.IsMatch(txtEmail.Text))
{
// Email is not valid
}
I suggest that you use a Regular Expression like:
#"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
To validate the input of your textbox.
Example code:
private void button1_Click(object sender, EventArgs e)
{
Regex emailRegex = new Regex(#"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?
^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+
[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
if (emailRegex.IsMatch(textBox1.Text))
{
MessageBox.Show(textBox1.Text + "matches the expected format.", "Attention");
}
}
Edit: I found a better, more comprehensive Regex.

Categories