How to match strings using wildcards in C# and VB.NET

To match strings using wildcards in C# and VB.NET you can use the following snippet.
It will internally convert the wildcard string to a Regex.

The Console-Output of this sample will be:

C:\Test\myFile01.xml
C:\Test\myFile02.xml

Sample C#

#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

#endregion

namespace de.fesslersoft.RegexWildCard
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var fileList = new List<String>();
            fileList.Add(@"C:\Test\myFile01.xml");
            fileList.Add(@"C:\Test\myFile02.xml");
            fileList.Add(@"C:\Test\myFolder01.xml");
            fileList.Add(@"C:\Test\myFolder02.xml");

            var wildCard = new Wildcard("*File*.xml", RegexOptions.IgnoreCase);
            foreach (var file in fileList.Where(file => wildCard.IsMatch(file)))
            {
                Console.WriteLine(file);
            }
            Console.Read();
        }
    }


    public class Wildcard : Regex
    {
        public Wildcard(string pattern) : base(ToRegex(pattern))
        {
        }

        public Wildcard(string pattern, RegexOptions options) : base(ToRegex(pattern), options)
        {
        }

        public static string ToRegex(string pattern)
        {
            return "^" + Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".") + "$";
        }
    }
}

Sample VB.NET (autoconverted)

#Region ""

Imports System.Collections.Generic
Imports System.Linq
Imports System.Text.RegularExpressions

#End Region

Namespace de.fesslersoft.RegexWildCard
	Friend Class Program
		Private Shared Sub Main(args As String())
			Dim fileList = New List(Of [String])()
			fileList.Add("C:\Test\myFile01.xml")
			fileList.Add("C:\Test\myFile02.xml")
			fileList.Add("C:\Test\myFolder01.xml")
			fileList.Add("C:\Test\myFolder02.xml")

			Dim wildCard = New Wildcard("*File*.xml", RegexOptions.IgnoreCase)
			For Each file As var In fileList.Where(Function(file) wildCard.IsMatch(file))
				Console.WriteLine(file)
			Next
			Console.Read()
		End Sub
	End Class


	Public Class Wildcard
		Inherits Regex
		Public Sub New(pattern As String)
			MyBase.New(ToRegex(pattern))
		End Sub

		Public Sub New(pattern As String, options As RegexOptions)
			MyBase.New(ToRegex(pattern), options)
		End Sub

		Public Shared Function ToRegex(pattern As String) As String
			Return "^" + Escape(pattern).Replace("\*", ".*").Replace("\?", ".") + "$"
		End Function
	End Class
End Namespace

Please rate this snippet

How to order a dictionary by Value in C# and VB.NET

To order/sort a dictionary by Value in C# and VB.NET you can use the snippet below.

Sample C#

MyDict = MyDict.OrderBy(x => x.Value).ToDictionary(x => x.Key, x => x.Value);

Sample VB.NET

MyDict = MyDict.OrderBy(Function(x) x.Value).ToDictionary(Function(x) x.Key, Function(x) x.Value)

Please rate this snippet

How to check if a printer exists in C# and VB.NET

To check if a printer exists in C# and VB.NET you can use the following snippet.

Sample C#

public static bool PrinterExists(string printerName)
{
	if (String.IsNullOrEmpty(printerName)) {  throw new ArgumentNullException("printerName");}
	return PrinterSettings.InstalledPrinters.Cast<string>().Any(name => printerName.ToUpper().Trim() == name.ToUpper().Trim());
}

Sample VB.NET

Public Shared Function PrinterExists(printerName As String) As Boolean
	If String.IsNullOrEmpty(printerName) Then
		Throw New ArgumentNullException("printerName")
	End If
	Return PrinterSettings.InstalledPrinters.Cast(Of String)().Any(Function(name) printerName.ToUpper().Trim() = name.ToUpper().Trim())
End Function

Please rate this snippet

How to get Devexpress Wizardpage by Name in C# and VB.NET

To get Devexpress Wizardpage by Name in C# and VB.NET you can use the following snippet.

Sample C#

public static WizardPage GetWizardPageByName(WizardControl wizard, string name)
{
	var controls = wizard.Controls.Find(name, false);
	if (controls.Length > 0 && controls[0] is WizardPage)
	{
		return controls[0] as WizardPage;
	}
	return null;
}

Sample VB.NET

Public Shared Function GetWizardPageByName(wizard As WizardControl, name As String) As WizardPage
	Dim controls = wizard.Controls.Find(name, False)
	If controls.Length > 0 AndAlso TypeOf controls(0) Is WizardPage Then
		Return TryCast(controls(0), WizardPage)
	End If
	Return Nothing
End Function

Please rate this snippet

How to set a Property Value by Name in C# and VB.NET

To set a Property Value by Name in C# and VB.NET you can use the following snippet.

Sample C#

public static bool SetPropertyByName(this Object obj, string name, Object value)
{
	var prop = obj.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
	if (null == prop || !prop.CanWrite) return false;
	prop.SetValue(obj, value, null);
	return true;
}

Sample VB.NET

Public Shared Function SetPropertyValueByName(obj As [Object], name As String, value As [Object]) As Boolean
	Dim prop = obj.[GetType]().GetProperty(name, BindingFlags.[Public] Or BindingFlags.Instance)
	If prop Is Nothing OrElse Not prop.CanWrite Then
		Return False
	End If
	prop.SetValue(obj, value, Nothing)
	Return True
End Function

Please rate this snippet

How to get Enum by Descritption Attribute in C# and VB.NET

To get Enum by Descritption Attribute in C# and VB.NET you can use the following snippet.

Sample C#

public static T GetEnumFromDescriptionAttribute<T>(string description)
{
	var type = typeof(T);
	if (!type.IsEnum) throw new InvalidOperationException();
	foreach (var fieldInfo in type.GetFields())
	{
		var descriptionAttribute = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) as DescriptionAttribute;
		if (descriptionAttribute != null)
		{
			if (descriptionAttribute.Description != description) continue;
			return (T)fieldInfo.GetValue(null);
		}
		if (fieldInfo.Name != description) continue;
		return (T)fieldInfo.GetValue(null);
	}
	return default(T);
}

Sample VB.NET

Public Shared Function GetEnumFromDescriptionAttribute(Of T)(description As String) As T
	Dim type = GetType(T)
	If Not type.IsEnum Then
		Throw New InvalidOperationException()
	End If
	For Each fieldInfo As var In type.GetFields()
		Dim descriptionAttribute = TryCast(Attribute.GetCustomAttribute(fieldInfo, GetType(DescriptionAttribute)), DescriptionAttribute)
		If descriptionAttribute IsNot Nothing Then
			If descriptionAttribute.Description <> description Then
				Continue For
			End If
			Return DirectCast(fieldInfo.GetValue(Nothing), T)
		End If
		If fieldInfo.Name <> description Then
			Continue For
		End If
		Return DirectCast(fieldInfo.GetValue(Nothing), T)
	Next
	Return Nothing
End Function

Please rate this snippet

How to style a link by filetype in CSS

To style a link by filetype in CSS you can use the following snippet.

Sample CSS

a[href$=".exe"] { background: url(icons/exe.png) left center no-repeat; padding-left: 50px; }
a[href$=".rar"] { background: url(icons/rar.png) left center no-repeat; padding-left: 50px; }
a[href$=".doc"] { background: url(icons/doc.png) left center no-repeat; padding-left: 50px; }
a[href$=".pdf"] { background: url(icons/pdf.png) left center no-repeat; padding-left: 50px; }
a[href$=".zip"] { background: url(icons/zip.png) left center no-repeat; padding-left: 50px; }
a[href$=".html"] { background: url(icons/link.png) left center no-repeat; padding-left: 50px; }

Please rate this snippet

How to read a textfile line by line in VBA

To read a textfile line by line in VBA you can use the following snippet.
To read a textfile complete into a string you can use How to read a textfile in VBA.

Sample VBA

public sub ReadTextFileLinebyLine()
    Dim sFileName As String
    Dim iFile As Integer
    Dim sLine As String

	on error goto errorhandler
    sFileName = "C:\Users\Codesnippets\Desktop\Test.txt"
	
	If Len(Dir$(sFileName)) = 0 Then
        Exit Sub
    End If

    iFile = FreeFile()
    Open sFileName For Input As iFile

    Do While Not EOF(iFile)
        Line Input #iFile, sLine
        Debug.Print sLine 
    Loop

    Close iFile
	exit sub
	
errorhandler:
'handle the error your way
End Sub

Please rate this snippet

How to get a word by index in C# and VB.NET

To get a word by index in C# and VB.NET you can use the following snippet.

Sample C#

public static string GetWordByIndex(string input, int index)
{
	try
	{
		var words = input.Split(' ');
		if ((index < 0) || (index > words.Length - 1))
		{
			throw new IndexOutOfRangeException("Index out of range!");
		}
		return words[index];
	}
	catch (Exception ex)
	{
		//handle the exception your way
		return string.Empty;
	}
}

Sample VB.NET

Public Shared Function GetWordByIndex(input As String, index As Integer) As String
	Try
		Dim words = input.Split(" ")
		If (index < 0) OrElse (index > words.Length - 1) Then
			Throw New IndexOutOfRangeException("Index out of range!")
		End If
		Return words(index)
	Catch ex As Exception
		'handle the exception your way
		Return String.Empty
	End Try
End Function

Please rate this snippet