How to get the executable filename in C# and VB.NET

To get the executable filename in C# and VB.NET you can use one the following methods.

Sample C#

//prefered way to retrieve exe filename
Console.WriteLine(Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName));
 

Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); //can cause problems when using click once, also this property does not always returns the right result.

Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().Location)); //can fail when used in wcf application.
Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase)); //better if shadow copy feature is active, but can fail when used in wcf application
Console.WriteLine(Path.GetFileName(Assembly.GetEntryAssembly().Location));

Sample VB.NET

'prefered way to retrieve exe filename
Console.WriteLine(Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName))


Console.WriteLine(AppDomain.CurrentDomain.FriendlyName)
'can cause problems when using click once, also this property does not always returns the right result.
Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().Location))
'can fail when used in wcf application.
Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase))
'better if shadow copy feature is active, but can fail when used in wcf application
Console.WriteLine(Path.GetFileName(Assembly.GetEntryAssembly().Location))

Please rate this snippet

How to round to X decimal places in C# and VB.NET

To round to X decimal places in C# and VB.NET you can use one of the following methods.
Take a look at the output image to see the results.

Sample ConsoleApp in C#

static void Main(string[] args)
{
	decimal input = Decimal.Parse("3,546932");
	decimal inputZero = Decimal.Zero;
	decimal inputShort = Decimal.Parse("3,545");
	decimal inputShorter = 1;

	Console.WriteLine("######################################################################");
	Console.WriteLine("");
	Console.WriteLine("Testinput1:\t{0}", input);
	Console.WriteLine("Testinput2:\t{0}", inputZero);
	Console.WriteLine("Testinput3:\t{0}", inputShort);
	Console.WriteLine("Testinput4:\t{0}", inputShorter);
	Console.WriteLine("");

	Console.WriteLine("########## using decimal.Round AwayFromZero 2 Decimals ##########");
	Console.WriteLine("");
	Console.WriteLine("Output 1:\t{0}",decimal.Round(input, 2, MidpointRounding.AwayFromZero));
	Console.WriteLine("Output 2:\t{0}", decimal.Round(inputShort, 2, MidpointRounding.AwayFromZero));
	Console.WriteLine("Output 3:\t{0}", decimal.Round(inputShorter, 2, MidpointRounding.AwayFromZero));
	Console.WriteLine("Output 4:\t{0}", decimal.Round(inputZero, 2, MidpointRounding.AwayFromZero));
	Console.WriteLine("");

	Console.WriteLine("########## using decimal.Round ToEven 2 Decimals ##########");
	Console.WriteLine("");
	Console.WriteLine("Output 1:\t{0}", decimal.Round(input, 2, MidpointRounding.ToEven));
	Console.WriteLine("Output 2:\t{0}", decimal.Round(inputShort, 2, MidpointRounding.ToEven));
	Console.WriteLine("Output 3:\t{0}", decimal.Round(inputShorter, 2, MidpointRounding.ToEven));
	Console.WriteLine("Output 4:\t{0}", decimal.Round(inputZero, 2, MidpointRounding.ToEven));
	Console.WriteLine("");

	Console.WriteLine("########## using .ToString(\"0.00\") 2 Decimals ##########");
	Console.WriteLine("");
	Console.WriteLine("Output 1:\t{0}", input.ToString("0.00"));
	Console.WriteLine("Output 2:\t{0}", inputShort.ToString("0.00"));
	Console.WriteLine("Output 3:\t{0}", inputShorter.ToString("0.00"));
	Console.WriteLine("Output 4:\t{0}", inputZero.ToString("0.00"));
	Console.WriteLine("");

	Console.WriteLine("########## using .ToString(\"0.00\") 5 Decimals ##########");
	Console.WriteLine("");
	Console.WriteLine("Output 1:\t{0}", input.ToString("0.00000"));
	Console.WriteLine("Output 2:\t{0}", inputShort.ToString("0.00000"));
	Console.WriteLine("Output 3:\t{0}", inputShorter.ToString("0.00000"));
	Console.WriteLine("Output 4:\t{0}", inputZero.ToString("0.00000"));
	Console.WriteLine("");

	Console.Read();
}

Sample ConsoleApp in VB.NET

Private Shared Sub Main(args As String())
	Dim input As Decimal = [Decimal].Parse("3,546932")
	Dim inputZero As Decimal = [Decimal].Zero
	Dim inputShort As Decimal = [Decimal].Parse("3,545")
	Dim inputShorter As Decimal = 1

	Console.WriteLine("######################################################################")
	Console.WriteLine("")
	Console.WriteLine("Testinput1:" & vbTab & "{0}", input)
	Console.WriteLine("Testinput2:" & vbTab & "{0}", inputZero)
	Console.WriteLine("Testinput3:" & vbTab & "{0}", inputShort)
	Console.WriteLine("Testinput4:" & vbTab & "{0}", inputShorter)
	Console.WriteLine("")

	Console.WriteLine("########## using decimal.Round AwayFromZero 2 Decimals ##########")
	Console.WriteLine("")
	Console.WriteLine("Output 1:" & vbTab & "{0}", Decimal.Round(input, 2, MidpointRounding.AwayFromZero))
	Console.WriteLine("Output 2:" & vbTab & "{0}", Decimal.Round(inputShort, 2, MidpointRounding.AwayFromZero))
	Console.WriteLine("Output 3:" & vbTab & "{0}", Decimal.Round(inputShorter, 2, MidpointRounding.AwayFromZero))
	Console.WriteLine("Output 4:" & vbTab & "{0}", Decimal.Round(inputZero, 2, MidpointRounding.AwayFromZero))
	Console.WriteLine("")

	Console.WriteLine("########## using decimal.Round ToEven 2 Decimals ##########")
	Console.WriteLine("")
	Console.WriteLine("Output 1:" & vbTab & "{0}", Decimal.Round(input, 2, MidpointRounding.ToEven))
	Console.WriteLine("Output 2:" & vbTab & "{0}", Decimal.Round(inputShort, 2, MidpointRounding.ToEven))
	Console.WriteLine("Output 3:" & vbTab & "{0}", Decimal.Round(inputShorter, 2, MidpointRounding.ToEven))
	Console.WriteLine("Output 4:" & vbTab & "{0}", Decimal.Round(inputZero, 2, MidpointRounding.ToEven))
	Console.WriteLine("")

	Console.WriteLine("########## using .ToString(""0.00"") 2 Decimals ##########")
	Console.WriteLine("")
	Console.WriteLine("Output 1:" & vbTab & "{0}", input.ToString("0.00"))
	Console.WriteLine("Output 2:" & vbTab & "{0}", inputShort.ToString("0.00"))
	Console.WriteLine("Output 3:" & vbTab & "{0}", inputShorter.ToString("0.00"))
	Console.WriteLine("Output 4:" & vbTab & "{0}", inputZero.ToString("0.00"))
	Console.WriteLine("")

	Console.WriteLine("########## using .ToString(""0.00"") 5 Decimals ##########")
	Console.WriteLine("")
	Console.WriteLine("Output 1:" & vbTab & "{0}", input.ToString("0.00000"))
	Console.WriteLine("Output 2:" & vbTab & "{0}", inputShort.ToString("0.00000"))
	Console.WriteLine("Output 3:" & vbTab & "{0}", inputShorter.ToString("0.00000"))
	Console.WriteLine("Output 4:" & vbTab & "{0}", inputZero.ToString("0.00000"))
	Console.WriteLine("")

	Console.Read()
End Sub

OUTPUT

Decimal Place Formatting

Decimal Place Formatting

Please rate this snippet

How to get the Youtube VideoId from Url in C# and VB.NET

To get the Youtube VideoId from an Url in C# and VB.NET you can use the following snippet.
It matches these 18 type of Youtube Links (Sample Data):

Sample Input

  • http://youtu.be/AAAAAAAAA01
  • http://www.youtube.com/embed/watch?feature=player_embedded&v=AAAAAAAAA02
  • http://www.youtube.com/embed/watch?v=AAAAAAAAA03
  • http://www.youtube.com/embed/v=AAAAAAAAA04
  • http://www.youtube.com/watch?v=AAAAAAAAA06
  • www.youtube.com/watch?v=AAAAAAAAA07
  • www.youtu.be/AAAAAAAAA08
  • youtu.be/AAAAAAAAA09
  • http://www.youtube.com/watch?feature=player_embedded&v=AAAAAAAAA05
  • http://www.youtube.com/watch?v=i-AAAAAAA14&feature=related
  • http://www.youtube.com/attribution_link?u=/watch?v=AAAAAAAAA15&feature=share&a=9QlmP1yvjcllp0h3l0NwuA
  • http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&u=/watch?v=AAAAAAAAA16&feature=em-uploademail
  • http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&feature=em-uploademail&u=/watch?v=AAAAAAAAA17
  • http://www.youtube.com/v/A-AAAAAAA18?fs=1&rel=0
  • youtube.com/watch?v=AAAAAAAAA10
  • http://www.youtube.com/watch/AAAAAAAAA11
  • http://www.youtube.com/v/AAAAAAAAA12
  • http://www.youtube.com/v/AAAAAAAAA13
  • Sample C#

    using System.Linq;
    using System.Text.RegularExpressions;
    
    namespace de.fesslersoft.YoutubeRegexTest
    {
        internal static class Youtube
        {
            private const string YoutubeLinkRegex = "(?:.+?)?(?:\\/v\\/|watch\\/|\\?v=|\\&v=|youtu\\.be\\/|\\/v=|^youtu\\.be\\/)([a-zA-Z0-9_-]{11})+";
    
            internal static string GetVideoId(string input)
            {
                var regex = new Regex(YoutubeLinkRegex, RegexOptions.Compiled);
                foreach (Match match in regex.Matches(input))
                {
                    //Console.WriteLine(match);
                    foreach (var groupdata in match.Groups.Cast<Group>().Where(groupdata => !groupdata.ToString().StartsWith("http://") && !groupdata.ToString().StartsWith("https://") && !groupdata.ToString().StartsWith("youtu") && !groupdata.ToString().StartsWith("www.")))
                    {
                        return groupdata.ToString();
                    }
                }
                return string.Empty;
            }
        }
    }
    

    Sample VB.NET

    Imports System.Linq
    Imports System.Text.RegularExpressions
     
    Namespace de.fesslersoft.YoutubeRegexTest
        Friend NotInheritable Class Youtube
            Private Sub New()
            End Sub
            Private Const YoutubeLinkRegex As String = "(?:.+?)?(?:\/v\/|watch\/|\?v=|\&v=|youtu\.be\/|\/v=|^youtu\.be\/)([a-zA-Z0-9_-]{11})+"
     
            Friend Shared Function GetVideoId(input As String) As String
                Dim regex = New Regex(YoutubeLinkRegex, RegexOptions.Compiled)
                For Each match As Match In regex.Matches(input)
                    For Each data As Group In match.Groups.Cast(Of Group)().Where(Function(groupdata) Not groupdata.ToString().StartsWith("http://") AndAlso Not groupdata.ToString().StartsWith("https://") AndAlso Not groupdata.ToString().StartsWith("youtu") AndAlso Not groupdata.ToString().StartsWith("www."))
                        Return data.ToString()
                    Next
                Next
                Return String.Empty
            End Function
        End Class
    End Namespace
    

    Output / Sample

    var urlList = new List<String>
    {
    	"http://youtu.be/AAAAAAAAA01",
    	"http://www.youtube.com/embed/watch?feature=player_embedded&v=AAAAAAAAA02",
    	"http://www.youtube.com/embed/watch?v=AAAAAAAAA03",
    	"http://www.youtube.com/embed/v=AAAAAAAAA04",
    	"http://www.youtube.com/watch?feature=player_embedded&v=AAAAAAAAA05",
    	"http://www.youtube.com/watch?v=AAAAAAAAA06",
    	"www.youtube.com/watch?v=AAAAAAAAA07",
    	"www.youtu.be/AAAAAAAAA08",
    	"youtu.be/AAAAAAAAA09",
    	"youtube.com/watch?v=AAAAAAAAA10",
    	"http://www.youtube.com/watch/AAAAAAAAA11",
    	"http://www.youtube.com/v/AAAAAAAAA12",
    	"http://www.youtube.com/v/AAAAAAAAA13",
    	"http://www.youtube.com/watch?v=i-AAAAAAA14&feature=related",
    	"http://www.youtube.com/attribution_link?u=/watch?v=AAAAAAAAA15&feature=share&a=9QlmP1yvjcllp0h3l0NwuA",
    	"http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&u=/watch?v=AAAAAAAAA16&feature=em-uploademail",
    	"http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&feature=em-uploademail&u=/watch?v=AAAAAAAAA17",
    	"http://www.youtube.com/v/A-AAAAAAA18?fs=1&rel=0"
    };
    
    foreach (var entry in urlList)
    {
    	Console.WriteLine(Youtube.GetVideoId(entry));
    }
    Console.Read();
    

    will result in the follwing output:

    Youtube VideoId Regex Console Window Output

    Youtube VideoId Regex Console Window Output

    A simpler but less matching solution can be found here: How to get the VideoID of a youtube video using Regex

    Please rate this snippet

    How to read a File to Textreader in C# and VB.NET

    To read a File to Textreader in C# and VB.NET you can use the following snippet.

    Sample C#

    TextReader reader = File.OpenText(@"C:\dummy.txt");
    

    Sample VB.NET

    Dim reader As TextReader = File.OpenText(@"C:\dummy.txt")
    

    Please rate this snippet

    How to read a file to string in Java

    To read a file to string in Java you can use the following snippet.

    Sample Java

    public static string readFileToString(FileInputStream _fileInputStream)
    {
    	try {  
    		DataInputStream dataInputStream = new DataInputStream (_fileInputStream);  
    		byte[] Bytes = new byte[dataInputStream.available ()];  
    		dataInputStream.readFully (Bytes);  
    		dataInputStream.close ();  
    		String result = new String (Bytes, 0, Bytes.length, "Cp850");  
    		return result;  
    	}  
    	catch (Exception e) {  
    		e.printStackTrace();  
    		return "";
    	} 
    }
    

    Please rate this snippet

    How to format bytes to human readable Size in Python

    To format bytes to human readable Size in Python you can use the following snippet.

    Sample Python

    fileSize = 12454162221
    for count in ['Bytes','KB','MB','GB']:
        if fileSize > -1024.0 and fileSize < 1024.0:
            print "%3.1f%s" % (fileSize, count)
        fileSize /= 1024.0
    print "%3.1f%s" % (fileSize, 'TB')
    

    Please rate this snippet

    How to format bytes to human readable Size in Javascript

    To format bytes to human readable Size in Javascript you can use the following snippet.

    Sample Javascript

    function BytesToHumanReadableSize(bytes){
    	if(!bytes) {return '0 bytes';}
        var sizeUnits = ['bytes','KB','MB','GB','TB','PB','EB','ZB','YB'];
        var calc = Math.floor( Math.log(bytes) / Math.log(1024) );
        calc = Math.min( Math.max(0,calc), sizeUnits.length-1);
        var bytesNew = Math.round((bytes/ Math.pow(1024,calc))*100)/100;
        return bytesNew + ' ' + sizeUnits[calc];
    }
    

    Please rate this snippet

    How to populate a XDocument from a String

    How to populate a XDocument from a String?

    Example C#

    string str = "This is Child 1This is Child 2";
    XDocument doc = XDocument.Parse(str);
    

    Example VB.NET

    Dim str As String = "This is Child 1This is Child 2"
    Dim doc As XDocument = XDocument.Parse(str)
    

    see the msdn for more informations XDocument.Parse Method

    Please rate this snippet