<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>string Archive - Robert Skibbe</title>
	<atom:link href="https://robbelroot.de/blog/tag/string/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>alias RobbelRoot – Freelance Full Stack Developer .NET</description>
	<lastBuildDate>Tue, 07 Apr 2026 17:15:00 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://robbelroot.de/wp-content/uploads/2020/12/cropped-favicon-32x32.png</url>
	<title>string Archive - Robert Skibbe</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>PHP generate a UUID with ease in 2026</title>
		<link>https://robbelroot.de/blog/making-php-generate-a-uuid-with-ease-heres-how/</link>
					<comments>https://robbelroot.de/blog/making-php-generate-a-uuid-with-ease-heres-how/#comments</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Mon, 29 Jan 2024 04:00:00 +0000</pubDate>
				<category><![CDATA[General]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[PHP HowTo's]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[binary]]></category>
		<category><![CDATA[bytes]]></category>
		<category><![CDATA[convert]]></category>
		<category><![CDATA[create]]></category>
		<category><![CDATA[creating]]></category>
		<category><![CDATA[generate]]></category>
		<category><![CDATA[generating]]></category>
		<category><![CDATA[guid]]></category>
		<category><![CDATA[help]]></category>
		<category><![CDATA[hex]]></category>
		<category><![CDATA[id]]></category>
		<category><![CDATA[identifier]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[print]]></category>
		<category><![CDATA[printf]]></category>
		<category><![CDATA[random]]></category>
		<category><![CDATA[server]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[uuid]]></category>
		<category><![CDATA[uuid4]]></category>
		<category><![CDATA[vsprintf]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=7715</guid>

					<description><![CDATA[<p>To make PHP generate a UUID, the most basic way would be using the native &#8222;uniqid&#8220; function. However, keep in mind, that this one isn&#8217;t an ID considering the known UUID standards (being UUIDs, versions 1-5). If you want to generate these UUIDs, you should take a well known and &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/making-php-generate-a-uuid-with-ease-heres-how/">PHP generate a UUID with ease in 2026</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/01/HowTo-make-PHP-generate-uuids-tutorial.png"><img fetchpriority="high" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/01/HowTo-make-PHP-generate-uuids-tutorial.png" alt="HowTo make PHP generate uuids tutorial" class="wp-image-7720" title="HowTo make PHP generate uuids tutorial"/></a><figcaption class="wp-element-caption">How to make PHP generate uuids tutorial</figcaption></figure>



<p><strong>To make PHP generate a UUID, the most basic way would be using the native &#8222;uniqid&#8220; function. However, keep in mind, that this one isn&#8217;t an ID considering the known UUID standards (being UUIDs, versions 1-5). If you want to generate these UUIDs, you should take a well known and tested library like ramsey/uuid.</strong></p>






<h2 class="wp-block-heading" id="you-want-to-make-php-generate-uuids-for-you">You want to make PHP generate UUIDs for you!?</h2>



<p>I welcome you to todays post on &#8222;How to make <strong>PHP generate a UUID</strong> for you&#8220;. In this post I will dive into<strong> </strong>the thing called <strong><a href="https://en.wikipedia.org/wiki/Universally_unique_identifier" target="_blank" rel="noreferrer noopener">universally unique identifiers</a></strong>. Those &#8222;special kind&#8220; identifiers are – as the name obviously suggests – for uniquely identifying &#8222;things&#8220;.</p>


<p class="rr-alert info" style="background:#e3f7fc;"><img decoding="async" alt="Info notice" src="https://robbelroot.de/wp-content/themes/pinboard-child/imgs/info.png"><span style="color:black;align-self: center;">If you would like to skip the &#8222;blabla&#8220;, <a href="#php-generate-a-uuid-the-code">jump to the manual creation here</a>. If you would like a short library based example, <a href="#using-ramsey-uuid">click here</a>. I would encourage you though, to study the <a href="#uuid-versions">different versions of UUIDs</a>.</span></p>



<p>There are <strong>different versions of UUIDs</strong>, mainly you can number them from versions 1 to 7. Many projects nowadays require a new way of generating that unique identifier for like your entities. It doesn&#8217;t matter if it&#8217;s stored in a good old<a href="https://www.mysql.com/" target="_blank" rel="noreferrer noopener"><strong>MySQL Database</strong></a>, or in one of the <strong><a href="https://en.wikipedia.org/wiki/Document-oriented_database" target="_blank" rel="noreferrer noopener">document based alternatives</a></strong>.</p>



<p>Using a different approach than those normal, incremental &#8222;1, 2, ..&#8220; ids, has become more and more popular. This doesn&#8217;t only apply for the developers side, customers and other involved parties actually want something else, too. So let&#8217;s get into the background story and later into how we can actually create/generate one.</p>



<h2 class="wp-block-heading" id="the-background-story-php-generate-uuid-s">The background story – PHP generate <strong>UUID</strong>&#8217;s</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/01/Background-story-PHP-generate-uuids.jpg"><img decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/01/Background-story-PHP-generate-uuids.jpg" alt="Background story - PHP generate uuids" class="wp-image-7743" title="Background story - PHP generate uuids"/></a><figcaption class="wp-element-caption">Background story &#8211; PHP generate UUIDs</figcaption></figure>



<p>Before we actually start thinking about code, we could also <strong>start from a little different angle</strong>. So imagine having a graphical user interface, like most of the time, with some kind of list. You got that usual screen with something like a table, which displays some data about the listed entities.</p>



<p>So far this isn&#8217;t really exciting, I know, but what comes into your mind, when thinking about the first column? The first column inside that table, will usually display the unique identifier for that entity. So basically this will be an incrementing number, which starts at like 1 and is constantly and linearly growing.</p>



<p>Sure, there are some cases where people want to define another starting point like at 5000, but.. Here we are, already facing one of the common problems when using &#8222;normal&#8220; numbers.</p>



<h3 class="wp-block-heading" id="the-thing-with-guessability">The thing with guessability</h3>



<p>No matter, if typical numbers start at 300, or at 300000, you can always kinda guess, what could potentially be the next one. When you have one id, you can increment that by yourself and you could test &#8222;Hmm, what&#8217;s the next one about!?&#8220;. This is literally one thing, where some customers and developers argue about doing it different.</p>



<p>The main reason for the customer would mostly be, to hide actual counts from the end user. End users could guess from order number &#8222;5&#8220;, that this shop maybe just started. This could lead the end user to actually interpret more, maybe negative things into that.</p>



<p>Thoughts like &#8222;Hmm, this shop did just start, maybe it&#8217;s a scam..&#8220; could arise.</p>



<h3 class="wp-block-heading" id="being-able-to-generate-offline">Being able to generate offline</h3>



<p>Usually the approach of working with the database or entities in general, is like the following. You have that basic overview screen, where you click this sweet &#8222;+&#8220;-button and voila. After that, you will have your detail screen displayed, which is ready to get filled out.</p>



<p>You will most likely fill out that form in front of you and then press something like &#8222;confirm&#8220;, or &#8222;save&#8220;. This will call some kind of api in the background, which then creates that new entity for you. During that process, the database will be contacted as central unit, being responsible for generating the new ID.</p>



<p>Now think about what happens, when you can&#8217;t contact the database, if you&#8217;re offline. Well I think you are correct – usually nothing will happen.. At this point, UUIDs come in handy, as they can be generated offline and can still be unique!</p>



<h3 class="wp-block-heading" id="uniqueness-accross-systems-replications">Uniqueness accross systems &amp; replications</h3>



<p>Imagine you have that one online shop, where you already got thousands of orders, bills and more data. Now imagine building up on that one shop, where you want to export and import the data in another system. Well, if you&#8217;re using normal, incremental numbers, you could easily run into some id clashes.</p>



<p>With UUIDs on the other hand, this most likely won&#8217;t be the case (care for the different versions here). By the word &#8222;universally&#8220; of the full name &#8222;universally unique identifier&#8220; this might get clearer. As I already promised, I won&#8217;t go to deep on this aspect of UUID, maybe I&#8217;ll do so in a later post!</p>



<p>You can just keep in mind, that UUIDs will prevent clashing, even generated on different systems.</p>



<h2 class="wp-block-heading">What&#8217;s does the trend say?</h2>



<p>As I mentioned above, the typical UUID spectrum consists of different versions, being 1 &#8211; 5. They all have their different aspects and considerations, you have to be aware of. I would therefore encourage you to do some studies, before actually using, not to mention, even generating them for yourself.</p>



<p>Here&#8217;s a graphic, which could give you a small overview of like which UUID versions are relevant / trending. Usually, this trend counts for like &#8222;in general&#8220;, not only for PHP. Between, this graphic is from today&#8217;s date (25.03.2026) considering data from the last 12 months:</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2024/01/php-uuid-google-trends-legend-2026.png"><img decoding="async" width="1076" height="483" src="https://robbelroot.de/wp-content/uploads/2024/01/php-uuid-google-trends-legend-2026.png" alt="Google Trends – UUID versions v1 to v7 color legend – 2026" class="wp-image-19783"/></a><figcaption class="wp-element-caption">Google Trends – UUID versions v1 to v7 (except 5) color legend – 2026</figcaption></figure>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2024/01/php-uuid-google-trends-v1-v4-v7-2026.png"><img loading="lazy" decoding="async" width="1094" height="584" src="https://robbelroot.de/wp-content/uploads/2024/01/php-uuid-google-trends-v1-v4-v7-2026.png" alt="Google Trends – UUID version interest over time worldwide, past year 2026" class="wp-image-19786"/></a><figcaption class="wp-element-caption">Google Trends comparison of UUID versions v1, v2, v3, v4 &amp; v7 worldwide – last 12 months 2026</figcaption></figure>



<p>Looking at the data, UUID v4 leads with an average interest of 64, closely followed by the newcomer UUID v7 at 52 &#x27a1;&#xfe0f; a clear sign of rapid adoption since its standardization in 2024. UUID v1 and v2 show minimal interest. UUID v5 was excluded from the chart as its search volume is negligible compared to the others.</p>



<h2 class="wp-block-heading" id="uuid-versions">The different versions of UUIDs</h2>



<p>UUIDs (Universally Unique Identifiers) can be generated in different versions, each having a specific purpose. Of course, you need to be sure, that the underlying library (or even yourself) is correctly implementing these aspects. Here are the commonly recognized versions of UUIDs:</p>



<h3 class="wp-block-heading">UUID1 (Time-based)</h3>



<p>This version is generated from the current time and the MAC address of the computer generating the UUID. It is unique within a particular network and time period.</p>



<h3 class="wp-block-heading">UUID2 (DCE Security)</h3>



<p>It&#8217;s pretty similar to UUID version 1, but it has support for <strong><a href="https://de.wikipedia.org/wiki/Distributed_Computing_Environment">DCE security</a></strong>. It&#8217;s not pretty much used from my experience – supported by the shown data from above, as well.</p>



<h3 class="wp-block-heading">UUID3 (Name-based, MD5 hash)</h3>



<p>This UUID version is generated from a namespace identifier and an arbitrary name. It uses MD5 hashing to create a UUID based on the namespace and name.</p>



<h3 class="wp-block-heading">UUID4 (Random)</h3>



<p>This is – in my experience and according to the above data – still the most widely used UUID version. It&#8217;s generated using random or pseudo-random numbers and provides a high probability of uniqueness. However, UUID v7 is catching up fast (see the trend data above).</p>



<h3 class="wp-block-heading">UUID5 (Name-based, SHA-1 hash)</h3>



<p>The version 5 UUID is pretty similar to version 3, but it uses SHA-1 (Secure Hash Algorithm) hashing instead of MD5 (the message digest algorithm).</p>



<p>Note: UUID v5 is not included in the Google Trends comparison above, as its search interest is too low to be meaningfully compared to v1, v4 and v7.</p>



<h3 class="wp-block-heading">UUID7 (Time-ordered, since RFC 9562 — 2024)</h3>



<p>UUID version 7 was officially standardized in May 2024 (RFC 9562) and is gaining rapid adoption. Unlike UUID4, it is time-ordered — meaning UUIDs generated later will always sort higher. This greatly improves database index performance compared to random UUID4.</p>



<p>The ramsey/uuid library supports UUID7 since version 4.7.0:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$uuid7 = Uuid::uuid7();</pre>



<p>If you are starting a new project in 2026, UUID7 is worth considering over UUID4 for database-backed entities.</p>



<h2 class="wp-block-heading" id="disadvantages-of-using-uuids">Disadvantages of using UUIDs</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/01/Disadvantages-of-using-uuids.jpg"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/01/Disadvantages-of-using-uuids.jpg" alt="Disadvantages of using uuids" class="wp-image-7760" title="Disadvantages of using uuids"/></a><figcaption class="wp-element-caption">Disadvantages of using UUIDs</figcaption></figure>



<p>I think every upside on a specific topic, will mostly have a downside as well, so let&#8217;s talk about that. On the one side, UUIDs will be that kind of added value from the aspects mentioned above. The other side like performance, indexability, etc. counts as well, for sure.</p>



<h3 class="wp-block-heading" id="indexability-and-performance">Indexability and performance</h3>



<p>When using uuids as keys inside your database, theres one big thing which primarily comes into your mind. I&#8217;m talking about the &#8222;indexability&#8220; and performance of actually storing the UUIDs inside your database tables. I can&#8217;t go to deep here, as there are already so many opinions on the web, so I would recommend doing further research.</p>



<p>One of the most reasons I&#8217;ve heard about not using UUIDs is like hard dropping performance when used on multiple joins. You should take a read on the web with search queries like &#8222;index fragmentation&#8220;.</p>



<h3 class="wp-block-heading" id="storage-size">Storage size</h3>



<p>I&#8217;ve seen it many times, where people stored the UUIDs as like &#8222;CHAR(36)&#8220;, means strings consisting of 36 characters. Actually, the UUIDs can be stored as a 128 bit = 16 byte, unsigned number, which is kinda more space optimized. Speaking about storage size in general I think, nowadays storage is much cheaper.</p>



<p>Especially if you can provide a better performance, I would preferably go for that over storage. For sure, this also depends on your use case and more things like budget, etc. Anyways i&#8217;m a big fan of optimization, where it actually makes sense.</p>



<p>If effort doesn&#8217;t outplay the result as hard as I don&#8217;t know, then it would make sense for me, so.. Generally you could say, that an UUID needs 4 times more space than like a 4 byte integer. It&#8217;s also really nice, that MySQL added more support for UUIDs on <strong><a href="https://dev.mysql.com/blog-archive/mysql-8-0-uuid-support/" target="_blank" rel="noreferrer noopener">their version 8</a></strong>.</p>



<h3 class="wp-block-heading" id="readability">Readability</h3>



<p>Another important aspect, which has its downside as well as its upside (as mentioned in &#8222;guessability&#8220;) is readability. While it can be nice for some folks out there, that you can&#8217;t really read those identifiers as easy as simple numbers. Other stress on having non readable identifiers, as like telling your customer on a request: &#8222;Hey, do you have an id for me?&#8220;.</p>



<p>For sure, this wouldn&#8217;t be a good experience, having your customer tell you like 36 characters. Theres another thing coming along with that readability point, especially when talking about URLs. You can tell by just looking at those URLs:</p>



<ul class="wp-block-list">
<li>/api/users/<strong>cc4f998b-29d8-4163-8bbe-2a44a1ccb2ac</strong></li>



<li>/api/users/<strong>55</strong></li>



<li>/api/users/<strong>my_nice_nickname</strong></li>
</ul>



<h2 class="wp-block-heading" id="php-generate-a-uuid-the-code">PHP generate a UUID / GUID – Manually</h2>



<p>After discussing some aspects about using those UUIDs, let&#8217;s now actually talk about generating a UUID with PHP. As I already mentioned, we can&#8217;t dive to deep into the different versions here, so I will focus on <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)" target="_blank" rel="noreferrer noopener"><strong>UUID version 4</strong></a>. Many online code examples use the <a href="https://www.php.net/manual/en/function.mt-rand.php" target="_blank" rel="noreferrer noopener"><strong>mt_rand PHP function</strong></a>, which is (as it states itself from the docs) not good for generating cryptographic thingys.</p>



<p>After finding different examples, I think this one here is the best one, being a mix of different answers. In the first step we need to choose the &#8222;correct&#8220; function for generating 16 random bytes. Below PHPs major version 7, this is supported by using the &#8222;<a href="https://www.php.net/manual/en/function.openssl-random-pseudo-bytes.php" target="_blank" rel="noreferrer noopener"><strong>openssl_random_pseudo_bytes</strong></a>&#8222;-function.</p>



<p>Starting with major PHP version 7 we can use the &#8222;<strong><a href="https://www.php.net/manual/en/function.random-bytes.php" target="_blank" rel="noreferrer noopener">random_bytes</a></strong>&#8222;-function. With an easy ternary operation, it could look like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// old version
// $data = PHP_MAJOR_VERSION &lt; 7 ? openssl_random_pseudo_bytes(16) : random_bytes(16);

$data = random_bytes(16); // PHP 7+ / PHP 8.x</pre>



<p>In the <strong>next step</strong> we are <strong>arranging the data</strong>, so that the version of the UUID, etc. actually matches:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$data[6] = chr(ord($data[6]) &amp; 0x0f | 0x40);    // Set version to 0100
$data[8] = chr(ord($data[8]) &amp; 0x3f | 0x80);    // Set bits 6-7 to 10</pre>



<p><strong>In the last step</strong> we are displaying the actual UUID by <strong>returning it as formatted string</strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">$uuid = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));</pre>



<p>You <strong>could </strong>also <strong>split up</strong> that <strong>last step into multiple</strong> other <strong>calls</strong>, but I think this doesn&#8217;t really help visibility here.</p>



<p>So the <strong>complete function</strong> could look like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// old
function get_guid() {
    $data = PHP_MAJOR_VERSION &lt; 7 ? openssl_random_pseudo_bytes(16) : random_bytes(16);
    $data[6] = chr(ord($data[6]) &amp; 0x0f | 0x40);    // Set version to 0100
    $data[8] = chr(ord($data[8]) &amp; 0x3f | 0x80);    // Set bits 6-7 to 10
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

// new
function get_guid(): string {
    $data = random_bytes(16); // requires PHP 7+, works in PHP 8.x
    $data[6] = chr(ord($data[6]) &amp; 0x0f | 0x40);    // Set version to 0100
    $data[8] = chr(ord($data[8]) &amp; 0x3f | 0x80);    // Set bits 6-7 to 10
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}</pre>



<p>You could also expand further by going the &#8222;Microsoft way&#8220;, with the &#8222;<strong><a href="https://www.php.net/manual/en/function.com-create-guid.php" target="_blank" rel="noreferrer noopener">com_create_guid</a></strong>&#8222;-function. This function will only (as far as I know) work, if you&#8217;re on a Windows based server. It will generate a UUID with prefixed and appended curly braces, hence the trim statement.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">function get_guid() {
    if (function_exists('com_create_guid') === true)
        return trim(com_create_guid(), '{}');
    $data = PHP_MAJOR_VERSION &lt; 7 ? openssl_random_pseudo_bytes(16) : random_bytes(16);
    $data[6] = chr(ord($data[6]) &amp; 0x0f | 0x40);    // Set version to 0100
    $data[8] = chr(ord($data[8]) &amp; 0x3f | 0x80);    // Set bits 6-7 to 10
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}</pre>



<h2 class="wp-block-heading" id="using-ramsey-uuid">Generating a UUID with ramsey/uuid</h2>



<p>Before doing your own experiments and implementing the versions of UUIDs for yourself, it&#8217;s probably better to use an existing library. Usually, I&#8217;m a fan of &#8222;doing things myself&#8220;, but when it comes to security and randomness, I would love to rely on broadly spreaded projects, that have been tested by many persons.</p>



<p>Of course you could have typical problems like the author abandoning the projects, etc. but in the end, you have to decide the common factors like:</p>



<ul class="wp-block-list">
<li>Maintainability</li>



<li>Security</li>



<li>Testing</li>



<li>Time-savings</li>



<li>&#8230;.</li>
</ul>



<p>So let&#8217;s now take a look at an example code from the <strong><a href="https://github.com/ramsey/uuid" target="_blank" rel="noreferrer noopener">ramsey/uuid library</a></strong>, feel free to visit the project on Github.</p>



<h3 class="wp-block-heading">Installing the library</h3>



<p>As with the most of PHP based libraries, we will install this one with composer as well. Open a terminal in your project folder and run the following installation command:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">composer require ramsey/uuid</pre>



<h3 class="wp-block-heading">Import and usage</h3>



<p>After you have installed the library, you can now import the corresponding classes. Put import statement on the usual upper part, of your code file. You can then just call the static helper functions, to generate a UUID of your desire.</p>



<p>We will generate a UUID4 in this case:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?php
namespace yournamespace;

// here's the important part...
use Ramsey\Uuid\Uuid;

// here's the generation of the UUID4 itself
$myUuid4 = Uuid::uuid4();</pre>



<h3 class="wp-block-heading">Formatting and stuff</h3>



<p>Keep in mind, that the previous example created an instance of the following class:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Ramsey\Uuid\Rfc4122\UuidV4</pre>



<p>If you want to do some formatting actions, you can use things – <strong><a href="https://uuid.ramsey.dev/en/stable/quickstart.html#install-with-composer" target="_blank" rel="noreferrer noopener">a</a><a href="https://uuid.ramsey.dev/en/stable/quickstart.html#install-with-composer">ccording to the documentation</a></strong> – like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="php" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?php
namespace yournamespace;

// import
use Ramsey\Uuid\Uuid;

// creation
$uuid = Uuid::uuid4();

// output
printf(
    "UUID: %s\nVersion: %d\n",
    $uuid->toString(),
    $uuid->getFields()->getVersion()
);</pre>



<div class="schema-faq wp-block-yoast-faq-block"><div class="schema-faq-section" id="faq-question-1774430427284"><strong class="schema-faq-question"><strong>What is the easiest way to generate a UUID in PHP?</strong></strong> <p class="schema-faq-answer">Use the ramsey/uuid library: <code>Uuid::uuid4()</code> generates a random UUID v4 in one line. For UUID v7 (time-ordered), use <code>Uuid::uuid7()</code>.</p> </div> <div class="schema-faq-section" id="faq-question-1774430463779"><strong class="schema-faq-question"><strong>Does PHP have a built-in UUID function?</strong></strong> <p class="schema-faq-answer">PHP has <code>uniqid()</code>, but it does not follow UUID standards (RFC 4122/9562). For proper UUIDs, use <code>random_bytes()</code> manually or the ramsey/uuid package.</p> </div> <div class="schema-faq-section" id="faq-question-1774430472195"><strong class="schema-faq-question"><strong>Should I use UUID v4 or UUID v7 in 2026?</strong></strong> <p class="schema-faq-answer">If database performance and sorting matter, use UUID v7 — it&#8217;s time-ordered and avoids index fragmentation. For simple, random IDs without a database, UUID v4 is still fine.</p> </div> </div>



<h2 class="wp-block-heading" id="related-posts">Related posts</h2>



<ul class="wp-block-list">
<li><strong><a href="https://robbelroot.de/blog/hacking-a-webshop/">Hacking a webshop</a></strong></li>



<li><strong><a href="https://robbelroot.de/blog/wordpress-loading-scripts-only-on-specific-pages-or-posts/" target="_blank" rel="noreferrer noopener">WordPress loading only page specific assets</a></strong></li>
</ul>
<p>Der Beitrag <a href="https://robbelroot.de/blog/making-php-generate-a-uuid-with-ease-heres-how/">PHP generate a UUID with ease in 2026</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/making-php-generate-a-uuid-with-ease-heres-how/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>C# String Format – Interpolation, Numbers, Dates (2026)</title>
		<link>https://robbelroot.de/blog/csharp-string-format-formatting-strings/</link>
					<comments>https://robbelroot.de/blog/csharp-string-format-formatting-strings/#comments</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Thu, 25 Aug 2022 03:05:06 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C# HowTo's]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[append]]></category>
		<category><![CDATA[c sharp]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[concat]]></category>
		<category><![CDATA[concatenation]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[format]]></category>
		<category><![CDATA[formatting]]></category>
		<category><![CDATA[helper]]></category>
		<category><![CDATA[interpolation]]></category>
		<category><![CDATA[method]]></category>
		<category><![CDATA[operator]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[tostring]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=11137</guid>

					<description><![CDATA[<p>With C# String Format you turn raw values into readable, locale-aware output. This post covers three approaches: concatenation, String.Format, and string interpolation. You will also learn how to format numbers, currencies, DateTimes, and custom objects with CultureInfo. How to format a String in C#? There are many situations where you &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/csharp-string-format-formatting-strings/">C# String Format – Interpolation, Numbers, Dates (2026)</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>With C# String Format you turn raw values into readable, locale-aware output. This post covers three approaches: concatenation, String.Format, and string interpolation. You will also learn how to format numbers, currencies, DateTimes, and custom objects with CultureInfo.</p>


<div style="box-sizing:border-box;margin:36px 0;border-radius:12px;overflow:hidden;background:#1a1a2e;position:relative;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
  <div style="position:absolute;inset:0;background-image:linear-gradient(rgba(255,255,255,0.03) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,0.03) 1px,transparent 1px);background-size:40px 40px;pointer-events:none;"></div>
  <div style="position:absolute;top:-60px;right:-60px;width:240px;height:240px;background:radial-gradient(circle,rgba(230,126,34,0.18) 0%,transparent 70%);pointer-events:none;"></div>
  <div style="position:relative;padding:32px 28px;">

        <div style="display:inline-block;font-size:11px;font-weight:700;letter-spacing:2.5px;text-transform:uppercase;color:#e67e22;margin-bottom:14px;border:1px solid rgba(230,126,34,0.35);border-radius:4px;padding:3px 10px;">Need help?</div>
    
        <p style="margin:0 0 10px 0;font-size:clamp(17px,4vw,21px);font-weight:700;color:#ffffff;line-height:1.35;">C# development for your project?</p>
    
        <p style="margin:0 0 24px 0;font-size:14px;color:rgba(255,255,255,0.65);line-height:1.7;max-width:540px;">I work with C# and .NET every day. Whether formatting logic, architecture, or complete applications, just get in touch.</p>
    
    <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:center;">

            <a href="https://robbelroot.de/contact/"
         style="display:inline-block;padding:12px 24px;background:#e67e22;color:#ffffff;font-size:14px;font-weight:700;text-decoration:none;border-radius:7px;letter-spacing:0.3px;transition:background .2s ease;white-space:nowrap;"
         onmouseover="this.style.background='#cf6d17'"
         onmouseout="this.style.background='#e67e22'"
      >→ Request a project</a>
      
      
    </div>
  </div>
</div>
	





<h2 class="wp-block-heading">How to format a String in C#?</h2>



<p>There are many situations where you need properly formatted strings. Imagine having an invoice, where the value would be like &#8222;14&#8220;. At first you could say: &#8222;Well, fourteen of what?&#8220; and usually you would like it to have two decimal points. But even things like displaying a list of persons inside a <a href="https://robbelroot.de/blog/the-wpf-listview-control-the-complete-guide/">WPF ListView</a> will touch the string formatting topic.</p>



<h3 class="wp-block-heading">The different approaches of formatting strings</h3>



<p>When it comes to formatting strings in C#, there are 3 main approaches:</p>



<ul class="wp-block-list">
<li>concatenating strings manually</li>



<li>using a function of the string class</li>



<li>making use of the new string interpolation feature</li>
</ul>



<p>Concatenation means joining multiple strings into one. I think the easiest example for this will be the one in the next section, which covers concatenating two name parts into a full name.</p>



<h2 class="wp-block-heading">Formatting a String by manual concatenation</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/08/csharp-String-Format-using-concatenation.png"><img loading="lazy" decoding="async" width="640" height="360" src="https://robbelroot.de/wp-content/uploads/2022/08/csharp-String-Format-using-concatenation.png" alt="C# String Format using concatenation" class="wp-image-11668" title="C# String Format using concatenation"/></a><figcaption class="wp-element-caption">C# String Format using concatenation</figcaption></figure>



<p>Look at the first method of formatting a string from above, we can see the basic concatenation. As already explained, this will form a brandnew string by concatenating multiple ones. Thankfully, you aren&#8217;t limitied to a specific count of strings here.</p>



<p>Let&#8217;s now take a look at the first little example of creating the mentioned full name string from name parts. We will create two basic variables for this in the first step, then we will combine them.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">string firstName = "John";
string lastName = "Doe";</pre>



<p>After creating those variables, we can now concatenate them into a complete new string. Keep in mind that C# strings are immutable and the common operators and functions will always create a new string.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">string fullName = firstName + " " + lastName;</pre>



<p>You can now say, that this was the actual most basic formatting of a string you could do, but what if it has to be a bit more complicated? What if you are in the actual need of giving a user the change to specify his own format style?</p>



<h2 class="wp-block-heading">How to format a String in C# &#8222;the old way&#8220;?</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/08/Formatting-csharp-strings-using-string-class-format-method.png"><img loading="lazy" decoding="async" width="640" height="360" src="https://robbelroot.de/wp-content/uploads/2022/08/Formatting-csharp-strings-using-string-class-format-method.png" alt="Formatting C# Strings using String Class Format method" class="wp-image-11670" title="Formatting C# Strings using String Class Format method"/></a><figcaption class="wp-element-caption">Formatting C# Strings using String Class Format method</figcaption></figure>



<p>The example from the section above was pretty common and there basically is no customization chance for the user. If someone uses your program and wants to like change the way this input data is ordered, he would have to swap the first and the last name. I mean sure, sometimes it isn&#8217;t necessary/wanted, but just sayin&#8216;!</p>



<p>Now let&#8217;s look at a little helper function from the NET frameworks <strong><a href="https://docs.microsoft.com/en-us/dotnet/api/system.string?view=net-6.0" target="_blank" rel="noreferrer noopener">string class</a></strong>, which is simply called &#8222;Format&#8220;. As the name already suggests it helps with – you guessed it – formatting strings. We will now use this function to replicate the same full name string from above.</p>



<p>To be able to do this, we should take a look at the function parameters first. There are <strong><a href="https://docs.microsoft.com/de-de/dotnet/api/system.string.format?view=net-6.0" target="_blank" rel="noreferrer noopener">different overloads</a></strong>, but we will focus the one having a string as the first parameter and an object parameter array as the second parameter. The first parameter wants to have some kind of formatting &#8222;formula&#8220; to do the actual formatting. The second one wants a list of objects to actually put them in the specified places. This is done by using curly braces containing the specific index of the corresponding object.</p>



<h3 class="wp-block-heading">Dynamically formatting a String</h3>



<p>We can pass any objects (currently being two strings) by separating each one through a comma. In the next example, I will pass the two name parts. Our first name variable will then have the index 0 and the last name will be at index 1.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">string firstName = "John";
string lastName= "Doe";
string fullName = string.Format("{0} {1}", firstName, lastName);</pre>



<p>Now you could actually let your user input some kind of format of his desire (if needed). In the next example I just switched out the order of names as mentioned above. This will create a new string with the contents: &#8222;Doe John&#8220; instead of &#8222;John Doe&#8220;.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// take this from like a TextBox, etc.
string userWantedFormat = "{1} {0}";
string firstName = "John";
string lastName= "Doe";
string fullName = string.Format(format, firstName, lastName);</pre>



<p>For sure you could also control those passed in names by adding and removing (even omitting) items to a list dynamically. Then you could also pass that list as a parameter, as the function is able to work with a list of any kind of objects as well.</p>



<h2 class="wp-block-heading">How to do a C# String Format with interpolation?</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/08/Using-String-interpolation-in-csharp.png"><img loading="lazy" decoding="async" width="640" height="360" src="https://robbelroot.de/wp-content/uploads/2022/08/Using-String-interpolation-in-csharp.png" alt="Using String interpolation in C#" class="wp-image-11672" title="Using String interpolation in C#"/></a><figcaption class="wp-element-caption">Using String interpolation in C#</figcaption></figure>



<p>I pretty much love the approach of formatting strings in C# the &#8222;modern&#8220; way, called &#8222;string interpolation&#8220;. This way, you can basically put the strings you want at the position of your desire – directly! Let&#8217;s now construct the above example by using the string interpolation technique.</p>



<p>Next to specifying the exact position, it&#8217;s pretty much easier to actually know what to put where. In the above example we could only say like &#8222;put string with index 0 here or there&#8220;, but what if the actual index changed? Will you still remember the correct position?</p>



<p>Here&#8217;s the example from above, but now with string interpolation. For this, we need to put a dollar sign in front of the string itself, then we can just put in those variable names by surrounding them with curly braces. In my opinion, this is much easier and clearer than all previous examples.</p>



<p>Like this, we can also forget about those stupid opening and closing tags of strings. With the omittance of the no longer needed &#8222;+&#8220;-signs, it&#8217;s even easier and less verbose.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">string firstName = "John";
string lastName = "Doe";
string fullName = $"{firstName} {lastName}";</pre>


<div style="box-sizing:border-box;margin:36px 0;border-radius:12px;overflow:hidden;background:#1a1a2e;position:relative;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
  <div style="position:absolute;inset:0;background-image:linear-gradient(rgba(255,255,255,0.03) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,0.03) 1px,transparent 1px);background-size:40px 40px;pointer-events:none;"></div>
  <div style="position:absolute;top:-60px;right:-60px;width:240px;height:240px;background:radial-gradient(circle,rgba(230,126,34,0.18) 0%,transparent 70%);pointer-events:none;"></div>
  <div style="position:relative;padding:32px 28px;">

        <div style="display:inline-block;font-size:11px;font-weight:700;letter-spacing:2.5px;text-transform:uppercase;color:#e67e22;margin-bottom:14px;border:1px solid rgba(230,126,34,0.35);border-radius:4px;padding:3px 10px;">Need help?</div>
    
        <p style="margin:0 0 10px 0;font-size:clamp(17px,4vw,21px);font-weight:700;color:#ffffff;line-height:1.35;">C# development for your project?</p>
    
        <p style="margin:0 0 24px 0;font-size:14px;color:rgba(255,255,255,0.65);line-height:1.7;max-width:540px;">I work with C# and .NET every day. Whether formatting logic, architecture, or complete applications, just get in touch.</p>
    
    <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:center;">

            <a href="https://robbelroot.de/contact/"
         style="display:inline-block;padding:12px 24px;background:#e67e22;color:#ffffff;font-size:14px;font-weight:700;text-decoration:none;border-radius:7px;letter-spacing:0.3px;transition:background .2s ease;white-space:nowrap;"
         onmouseover="this.style.background='#cf6d17'"
         onmouseout="this.style.background='#e67e22'"
      >→ Request a project</a>
      
      
    </div>
  </div>
</div>
	


<h2 class="wp-block-heading" id="how-to-format-numbers-and-currencies">How to format numbers and currencies?</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/08/How-to-format-numbers-to-strings-in-csharp.png"><img loading="lazy" decoding="async" width="640" height="360" src="https://robbelroot.de/wp-content/uploads/2022/08/How-to-format-numbers-to-strings-in-csharp.png" alt="How to format numbers to strings in C#" class="wp-image-11706" title="How to format numbers to strings in C#"/></a><figcaption class="wp-element-caption">How to format numbers to strings in C#</figcaption></figure>



<p>After only working on the basic first and last name example, we will go a step further right now. I mean, formatting strings to strings isn&#8217;t that hard at all, but let&#8217;s see, how it would look with more complex types. The first more complex (but still easy) type is a usual number, just like the invoice sum from the top of this post (being 14).</p>



<p>Usually – at least for me in germany here – you display the total sum of an invoice with two decimals. Next to those decimal points, you also use for example the Euro sign. Let&#8217;s try to use the basic representation of that number 14 displayed in the image above.</p>



<p>To do so, we can use one of the shown methods mentioned above:</p>



<ul class="wp-block-list">
<li>manual formatting</li>



<li>string class method called format</li>



<li>interpolating a string</li>
</ul>



<h3 class="wp-block-heading">Formatting with &#8222;ToString&#8220; object base function</h3>



<p>First, I will provide an example of doing this &#8222;manually&#8220;, by using the typical &#8222;ToString&#8220; function being inherited from the base class object. We will use the overload, where we can specify a format as string and the format will be &#8222;N2&#8220;. This stands for format a number &#8222;into&#8220; a string, but with two decimal points.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">decimal totalNet = 14.95M;
string displayValue = totalNet.ToString("N2");
// will result in displayValue being "14.95" in an en-US system setup</pre>



<h3 class="wp-block-heading" id="using-string-format-or-interpolation">Using string.format or interpolation</h3>



<p>The same results from above can be achieved with the same functionality from further above. I will use both other techniques here, as they are pretty much equal.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">decimal totalNet = 14.95M;
// using string.Format
string displayValue = string.Format(totalNet, "{0:N2}");
// using string interpolation
string displayValue = $"{totalNet:N2}";</pre>



<h3 class="wp-block-heading">Specifying a particular culture / language / locale</h3>



<p>As you can see in my comment, you will get some value for &#8222;displayValue&#8220; like &#8222;14.95&#8220;. Keep in mind, that this will be dependent on your language setting. You could also tell him, to use like the german language setting with another parameter called &#8222;FormatProvider&#8220;.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// dont forget the import!
// using System.Globalization;
// use either this
CultureInfo deDeCulture = new CultureInfo("de-DE");
// or this
CultureInfo enUsCulture = new CultureInfo("en-US");
decimal totalNet = 14.95M;
// provided as second parameter here
string displayValue = totalNet.ToString("N2", deDeCulture);
// and look at the changed displayValue variable en-US = 14.95, de-DE = 14,95</pre>



<p>To use string interpolation with a culture, you could create a &#8222;FormattableString&#8220; and use this instead of a normal one.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">decimal totalNet = 14.95M;
// this magically creates a FormattableString!
FormattableString displayValue = $"The total price is {totalNet:N2}.";
CultureInfo enUsCulture = new CultureInfo("en-US");
string message = displayValue.ToString(enUsCulture );
// en-US = 14.95, de-DE = 14,95</pre>



<h3 class="wp-block-heading">Setting the culture globally, not for each call</h3>



<p>In the next step, you could make it even &#8222;easier&#8220; – depending on the use case – by setting this &#8222;CultureInfo&#8220; more globally. Like this, you would override the system specific default setting by just providing another one. Take a look at the following snippet:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// dont forget to import
// using System.Threading;
CultureInfo deDeCulture = new CultureInfo("de-DE");
CultureInfo enUsCulture = new CultureInfo("en-US");
// overriding the system default to a specific value
Thread.CurrentThread.CurrentCulture = enUsCulture;</pre>



<p>All subsequent calls to formatting specific functions like &#8222;ToString&#8220; will now use the &#8222;enUsCulture&#8220; as default (overriding the system defaults).</p>



<h3 class="wp-block-heading">Ouputting currency-formatted strings</h3>



<p>After talking about the usual number style formatting, we can now try to display a simple currency aware number. This works pretty much the same by just changing one single letter. I changed &#8222;N2&#8220; (which stands for number with 2 decimals) to &#8222;C2&#8220; (which means currency with 2 decimals).</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// take a look at the previous examples for string.format and manual things as well
FormattableString displayValue = $"The total price is {totalNet:C2}.";
CultureInfo enUsCulture = new CultureInfo("en-US");
string message = displayValue.ToString(enUsCulture );</pre>



<h2 class="wp-block-heading">How to format DateTimes or more complex objects?</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/08/How-to-format-datetimes-or-custom-objects.png"><img loading="lazy" decoding="async" width="640" height="360" src="https://robbelroot.de/wp-content/uploads/2022/08/How-to-format-datetimes-or-custom-objects.png" alt="How to format datetimes or custom objects" class="wp-image-11740" title="How to format datetimes or custom objects"/></a><figcaption class="wp-element-caption">How to format datetimes or custom objects</figcaption></figure>



<p>In the next section we will take a closer look at formatting more comples objects instead of those simple numbers and stuff. I&#8217;m for example talking about the &#8222;<strong>DateTime</strong>&#8220; and other (maybe) custom classes you made yourself.</p>



<p>What if you have this customer which can be a private or a business customer and you want to use a C# String Format to display &#8222;him&#8220;? Are you going to display his business name, or his private first and last name? How do interpolate a string using this information?</p>



<h3 class="wp-block-heading">Formatting DateTimes</h3>



<p>Let&#8217;s first do some examples formatting an instance of the C# DateTime class. I will stay at using the string interpolation, but for sure, you can use the other techniques <strong><a href="#using-string-format-or-interpolation">from above</a></strong> as well. After displaying a simple date string, we will also go ahead with some month-ish and time-ish strings.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// using the current date and time for example
DateTime now = DateTime.Now;
// displaying a typical german date - 30.03.2023 for example
string displayValue = $"{now:dd.MM.yyyy}";
// displaying typical english date - care for escaping the backslashes, you could also
// omit the double backslashes and use the normal @ prefix like @$
string displayValue = $"{now:MM\\dd\\yyyy}";
// working with a time
string displayTimeValue = @$"{now:HH:mm}";</pre>



<h3 class="wp-block-heading">Formatting custom objects like a customer class instance</h3>



<p>In this last section we will take a look at formatting our custom made customer class. For sure, this will be a pretty simple class with like only a few properties &#8211; for displaying purposes. We will create two &#8222;types&#8220; of customers (which I would normally do otherwise, but now..): Business customers and private customers. The business customer will only have its company set, the private one will have a first and a last name.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public class Customer
{

  public string Company { get; set; }

  public string FirstName { get; set; }

  public string LastName { get; set; }

  public Customer(string company)
  {
    Company = company;
  }

  public Customer(string firstName, string lastName)
  {
    FirstName = firstName;
    LastName = lastName;
  }

}</pre>



<p>We could then create a private and a business customer like this:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Customer privateCustomer = new Customer("John", "Doe");
Customer businessCustomer = new Customer("Doe Max Profit ltd.");</pre>



<p>If you now try to format them like this, you will get some gibberish like &#8222;Customer: ProjectName.ClassName&#8220;. This is basically how objects without overriding of the &#8222;ToString&#8220; function will look alike.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">// will contain like Customer: ProjectName.Customer
string text = $"Customer: {privateCustomer}";</pre>



<p>So as mentioned as above, we only need to override the &#8222;ToString&#8220; function to make it easier for us. For sure, you could also just display some other properties/values. In this example, I will just prioritize the company name and if not provided, I will return the full name. If you need to iterate over multiple customers, see <a href="https://robbelroot.de/blog/csharp-for-each-iterating-the-objective-way/">C# ForEach</a>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public class Customer
{

  // ...
  // the the other stuff from above
  // ...

  public override ToString()
  {
    if (string.IsNullOrEmpty(Company)) {
      return Company;
    }
    return $"{FirstName} {LastName}";
  }
}</pre>



<p>Now take a look of the results of the following code lines:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Customer privateCustomer = new Customer("John", "Doe");
Customer businessCustomer = new Customer("Doe Max Profit ltd.");
// will contain Customer: John Doe
string text = $"Customer: {privateCustomer}";
// will contain Customer: Doe Max Profit ltd.
string text = $"Customer: {businessCustomer}";</pre>



<p>As seen in the comments, we will now be able to see some different and better looking results.</p>



<h2 class="wp-block-heading">FAQ</h2>



<div class="schema-faq wp-block-yoast-faq-block"><div class="schema-faq-section" id="faq-question-1775580490371"><strong class="schema-faq-question">What is the difference between String.Format and string interpolation in C#?</strong> <p class="schema-faq-answer">Both produce the same result. String interpolation (using the <code>$</code> prefix) is more readable because you place variables directly inside the string instead of referencing index numbers. For new code, prefer interpolation.</p> </div> <div class="schema-faq-section" id="faq-question-1775580535454"><strong class="schema-faq-question">How do I format a number with two decimal places in C#?</strong> <p class="schema-faq-answer">Use the format specifier <code>N2</code>, for example <code>totalNet.ToString("N2")</code> or <code>$"{totalNet:N2}"</code> with string interpolation. The result depends on the active CultureInfo (e.g. <code>14.95</code> for en-US, <code>14,95</code> for de-DE).</p> </div> <div class="schema-faq-section" id="faq-question-1775580542452"><strong class="schema-faq-question">How do I display a currency symbol when formatting in C#?</strong> <p class="schema-faq-answer">Use the <code>C</code> format specifier, e.g. <code>$"{price:C2}"</code>. The currency symbol is determined by the active CultureInfo: <code>$</code> for en-US, <code>€</code> for de-DE.</p> </div> <div class="schema-faq-section" id="faq-question-1775580550589"><strong class="schema-faq-question">How do I format a DateTime to a specific pattern in C#?</strong> <p class="schema-faq-answer">Use format specifiers inside <code>ToString</code> or string interpolation, e.g. <code>$"{now:dd.MM.yyyy}"</code> for a date or <code>$"{now:HH:mm}"</code> for time. You can combine patterns freely.</p> </div> </div>



<h2 class="wp-block-heading">Wrapping up</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/08/Wrapping-up.png"><img loading="lazy" decoding="async" width="640" height="360" src="https://robbelroot.de/wp-content/uploads/2022/08/Wrapping-up.png" alt="Wrapping up" class="wp-image-11757" title="Wrapping up"/></a><figcaption class="wp-element-caption">Wrapping up</figcaption></figure>



<p>C# offers three ways to format strings: manual concatenation, String.Format, and string interpolation. For new code, prefer interpolation as it is the most readable. Use <strong><a href="https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo?view=net-10.0" target="_blank" rel="noreferrer noopener">CultureInfo</a></strong> when your application needs to support multiple locales. For another practical C# example, check out <strong><a href="https://robbelroot.de/blog/how-to-use-the-csharp-linq-sum-function/" type="post" id="12014" target="_blank" rel="noreferrer noopener">C# LINQ Sum</a></strong>.</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/csharp-string-format-formatting-strings/">C# String Format – Interpolation, Numbers, Dates (2026)</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/csharp-string-format-formatting-strings/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>C# MD5 hashing in 2024</title>
		<link>https://robbelroot.de/blog/creating-a-csharp-md5-hash/</link>
					<comments>https://robbelroot.de/blog/creating-a-csharp-md5-hash/#comments</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Sat, 16 Jul 2022 03:42:14 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C# HowTo's]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[algorithm]]></category>
		<category><![CDATA[c sharp]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[coding]]></category>
		<category><![CDATA[create]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[hash]]></category>
		<category><![CDATA[hashing]]></category>
		<category><![CDATA[md5]]></category>
		<category><![CDATA[object]]></category>
		<category><![CDATA[salt]]></category>
		<category><![CDATA[snippet]]></category>
		<category><![CDATA[string]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=10976</guid>

					<description><![CDATA[<p>C# MD5 hashing nowadays Being in the need of creating a C# MD5 hash for one of my projects has been a while now. Due to one of my recent customer projects I got back to it and I noticed, that I don&#8217;t have a matching blog post. Well, so &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/creating-a-csharp-md5-hash/">C# MD5 hashing in 2024</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/C-MD5-Hashing.png"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/07/C-MD5-Hashing.png" alt="C# MD5 Hashing" class="wp-image-10994" title="C# MD5 Hashing"/></a><figcaption class="wp-element-caption">C# MD5 Hashing</figcaption></figure>






<h2 class="wp-block-heading">C# MD5 hashing nowadays</h2>



<p>Being in the need of creating a C# MD5 hash for one of my projects has been a while now. Due to one of my recent customer projects I got back to it and I noticed, that I don&#8217;t have a matching blog post. Well, so I just decided to create today&#8217;s blog post – enjoy &#x1f600;. As I don&#8217;t creating &#8222;half things&#8220; I will also go through some basics and FYI: We won&#8217;t use any kind of external library here.</p>



<p class="info-banner">&#x1f4a1; No time for blabla? No problem! If you prefer quick code snippets on creating C# MD5 hashes, just go to <strong><a href="#quick-examples">the quick examples section</a></strong>.</p>



<style>
.info-banner {
  background: #8acc47;
  padding: 2em;
  border-radius: 0.5em;
  color: whitesmoke;
}

.info-banner a {
 color: #2E86AB !important; 
}
</style>



<h2 class="wp-block-heading">Back to the basics – &#8222;data&#8220;?</h2>



<p>When trying to understand hashes we have to first go back some steps to the basic knowledge of storing data in general. Right away, we could begin with something like a simple string as &#8222;computer&#8220;. For sure there could be other data types, but a string or even a simple number is the perfect fight for the start, I think.</p>



<h3 class="wp-block-heading">How data is stored?</h3>



<p>Everyone&#8217;s talking about those things called &#8222;big data&#8220;, &#8222;data analyst&#8220; and whatsoever, but what actually is data? How is it being represented inside a modern day computer? In terms of a modern computer, data is actually stored as so called &#8222;bytes&#8220;. A single &#8222;byte&#8220; is actually the the smallest addressable unit of memory inside a computers context.</p>



<p>A byte actually consists of different single so called &#8222;bits&#8220;, in total 8 of them. The are &#8222;connected&#8220; and you can imagine it like in the following illustration:</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/C-SHA256-Hashing-The-basics-about-bytes-and-data.png"><img loading="lazy" decoding="async" width="555" height="300" src="https://robbelroot.de/wp-content/uploads/2022/07/C-SHA256-Hashing-The-basics-about-bytes-and-data.png" alt="C# MD5 Hashing – 8 bits form 1 byte" class="wp-image-10804" title="C# MD5 Hashing – 8 bits form 1 byte"/></a><figcaption class="wp-element-caption">C# MD5 Hashing – 8 bits form 1 byte</figcaption></figure>



<p>So in the image you can see, that there are 8 single bits acting together as one byte. Each single bit can be in one of two states: It can either be 1 (on), or otherwise it&#8217;s 0 (off). Any bits state change, will also change the overall value which is being represented by the byte.</p>



<h3 class="wp-block-heading">Some data examples</h3>



<p>At this point, I will try to provide some basic examples to help forming the basic knowledge. Please keep in mind, that I can&#8217;t go into this topic too deep. Of course you can go ahead and skip this part, if you are already thinking: &#8222;Nah, that&#8217;s only for babies, I already know everything there&#8220;.</p>



<h4 class="wp-block-heading">The first data example – the number 42</h4>



<p>In our first data example, we will take a look at the simple and basic number 42. Let&#8217;s see, how the data structure called byte – and therefore the bits – will represent this number.</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/A-basic-number-being-represented-as-byte.png"><img loading="lazy" decoding="async" width="489" height="171" src="https://robbelroot.de/wp-content/uploads/2022/07/A-basic-number-being-represented-as-byte.png" alt="Some bits representing the number 42" class="wp-image-10832" title="Some bits representing the number 42"/></a><figcaption class="wp-element-caption">Some bits representing the number 42</figcaption></figure>



<p>If you take a look at this binary / bitwise example from above, you can see, that there&#8217;s a mix of zeros and ones. Don&#8217;t think, that those bits are some kind of random, they follow a specific order and specific &#8222;values&#8220; being on or off. In the case of our number 42, the binary representation would be &#8222;00101010&#8220;.</p>



<h3 class="wp-block-heading">A basic &amp; quick explanation</h3>



<p>I will try to explain this basically like so: Each bit represents a single (and own) value itself, for example the outer right one being a 1. The next one – again, from the right side – is a 2 and then the chain continues. You could say: Start from right, being a 1 and double the value for each bit till you are on the left end.</p>



<p>We will talk more about this in just a few seconds, let&#8217;s now just focus on the &#8222;is on&#8220;, or &#8222;is off&#8220; at first. So when calculating the final value of that byte, you only take those &#8222;bit values&#8220; into account being on. In our example, this would sound like this:</p>



<ul class="wp-block-list">
<li>The bit on the outer right, being bit with value 1 is off, so just ignore it</li>



<li>Going to the second bit from the right, it&#8217;s on -&gt; take it&#8217;s value being 2</li>



<li>Next, the bit with value 4, is off, ignore again</li>



<li>And finally, the bit with value 32 is on -&gt; again, take it!</li>
</ul>



<p>Finally, we are having the following values (taking the &#8222;active&#8220; ones): 2, 8 and the 32. If you sum this up, you will have our desired number called 42 &#x1f389;! Here&#8217;s another image making it – hopefully – even clearer:</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/How-does-a-byte-represent-its-outer-value-C-Hash-basics.png"><img loading="lazy" decoding="async" width="828" height="369" src="https://robbelroot.de/wp-content/uploads/2022/07/How-does-a-byte-represent-its-outer-value-C-Hash-basics.png" alt="" class="wp-image-10838"/></a><figcaption class="wp-element-caption">A binary series of bits representing the number 42 – C# hashing basics</figcaption></figure>



<h3 class="wp-block-heading">How about a string – &#8222;MyPassword123&#8220;</h3>



<p>So after exploring the easy &#8222;one simple number only&#8220; example, we will now continue with a more complex string. Even though strings being more difficult on the first glimpse, they follow analog rules when being &#8222;stored&#8220;.</p>



<p>Right now, there would be the right place to start talking about something called character encodings. For now I will take a bit of a shortcut not going into those to deep, at this moment you should only take not of one thing: We are going to use the <strong><a href="https://en.wikipedia.org/wiki/ASCII" target="_blank" rel="noreferrer noopener">ASCI table</a></strong>. Next, let&#8217;s try to use the table for decoding our displayed number into a string representation.</p>



<p>Looking at the ASCII table and more specific at for example the letter &#8222;M&#8220;, you can see, that it has the code &#8222;077&#8220;. Just for fun right now, use your keyboard and hold down the &#8222;alt&#8220; key. Type the just found code and release your &#8222;alt&#8220; key again. Now you should notice an appearing &#8222;M&#8220; letter &#x1f60e; – nice!</p>



<h3 class="wp-block-heading">Looking at the M&#8217;s bitwise equivalent</h3>



<p>Now we are going to look at how the letter &#8222;M&#8220; is actually stored in its binary form. For this, we will check, how the number 77 would be displayed as binary number string.</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/The-number-42-represented-bitwise-C-SHA256.png"><img loading="lazy" decoding="async" width="585" height="224" src="https://robbelroot.de/wp-content/uploads/2022/07/The-number-42-represented-bitwise-C-SHA256.png" alt="" class="wp-image-10870"/></a><figcaption class="wp-element-caption">The number 77 being displayed as binary string</figcaption></figure>



<p>Using the little rulebook / algorithm learned from above, we will repeat it for this number / binary representation. Again, start from the right side having the value 1 for the first bit, then double it 7 times going to the left. In the end, check which bits are actually active and sum their values:</p>



<ul class="wp-block-list">
<li>Bit 1 -&gt; on = 1</li>



<li>Bit 3 -&gt; on = 4</li>



<li>Bit 4 -&gt; on = 8</li>



<li>Bit 7 -&gt; on = 64</li>
</ul>



<p>After listing those up, just sum those numbers and voila, we have our number &#8222;77&#8220;. Now I will actually save you from watching me repeat this process for each letter inside our string. Here is the complete string being represented as binary format:</p>



<pre class="wp-block-code"><code>01001101 01111001 01010000 01100001 01110011 01110011 01110111 01101111 01110010 01100100 00110001 00110010 00110011</code></pre>



<h2 class="wp-block-heading">What actually is a hash?</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/Is-this-a-hash-–-C-MD5.jpg"><img loading="lazy" decoding="async" width="556" height="500" src="https://robbelroot.de/wp-content/uploads/2022/07/Is-this-a-hash-–-C-MD5.jpg" alt="Is this a hash – C# MD5" class="wp-image-11027" title="Is this a hash – C# MD5"/></a><figcaption class="wp-element-caption">Is this a hash – C# MD5</figcaption></figure>



<p>After we now know (or knew before), how data is stored inside the computers memory, we will now go further. I think the most basic and easy explanation for a hash is as follows: &#8222;Take some value, put it into the hashing algorithm, get an output&#8220;. One important point is, that the same values being input, will result in the same output values.</p>



<p>Take at look at the following example hashes, before we continue:</p>



<ul class="wp-block-list">
<li>0cc175b9c0f1b6a831c399e269772661</li>



<li>973d98ac221d7e433fd7c417aa41027a</li>



<li>7618ca3b69910d35e18dd998d4b2830b</li>
</ul>



<p>Now I will show you same basic and important rules about hashing in general.</p>



<h3 class="wp-block-heading">The source is unknown</h3>



<p>The values from above seem to be a whole mess of nonsense, right? Actually, they aren&#8217;t, honestly you know at least two of those three values. This brings us to the second important point about hashes: You don&#8217;t know the origin / the source. A bit later, we will see, why this will be very important in some contexts.</p>



<h3 class="wp-block-heading">The output length is fixed</h3>



<p>Even though the first hash from above is only a small letter called &#8222;a&#8220;, it still seems pretty big. Looking at the second one – which was our password – it became a bit longer as well. The real interesting one is the last hash, where we actually computed a hash for a whole image file.</p>



<p>An MD5 is always 128 bits and therefore 32 hex digits long (means using the hexadecimal notation). The hex notation only needs 4 bits for each character, where you can easily calculate yourself: 128 / 4 = 32. Knowing this, you can store MD5 hashes in your database as char(64) field.</p>



<h3 class="wp-block-heading">It only goes in one direction</h3>



<p>The last important thing to note is, that hashes are irreversible, so you can hash, but can&#8217;t go back to source. Later, we will see why this could actually be a nice advantage instead of a problem. So now it&#8217;s time to step into the next sub-topic being &#8222;the why&#8220;.</p>



<h2 class="wp-block-heading">Why computing hashes?</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/C-SHA256-Why-you-should-hash.png"><img loading="lazy" decoding="async" width="640" height="360" src="https://robbelroot.de/wp-content/uploads/2022/07/C-SHA256-Why-you-should-hash.png" alt="Why computing hashes is sometimes important – C# MD5 hashing" class="wp-image-10864" title="Why computing hashes is sometimes important – C# MD5 hashing"/></a><figcaption class="wp-element-caption">Why computing hashes is sometimes important – C# MD5 hashing</figcaption></figure>



<p>After digging into the basic things, you could now ask yourself: &#8222;Why should I sometimes compute hashes in the first place?&#8220;. Theres one important example where get in touch with it almost everytime.</p>



<h3 class="wp-block-heading">Registration, signing in, etc.</h3>



<p>When thinking about hashing, my mind basically automatically switches to the topic of application logins. I think everyday we are going through plenty of authenticatino processes, where some hashing algorithm is in play (at least behind the scenes).</p>



<p>Imagine visiting your well known app login screen, you enter your credentials just as usual like the username &#8222;robert&#8220; and the password from above &#8222;MyPassword123&#8220;. When pressing the login button, it will mostly send a request to the server backend system. The code running on the server side will then try to find a corresponding user for the provided username. If no user could be found, then we will just get a typical matching error.</p>



<h3 class="wp-block-heading">Time for hashes</h3>



<p>After the steps above, the interesting part with hashes will happen next, so after an actual matching user could be found in the database. The system now hashes the provided (sent) password with the configured hashing algorithm. Then it will compare the just computed hash with the hash being fetched from the database – which is obviously stored there.</p>



<p>Now, go a step back and think about my argument saying: &#8222;Hashes can&#8217;t be reversed&#8220;, this is the time where this comes into play. Through the last years you will probably have heard about those typical news headlines like &#8222;200.000 user datasets have been stolen from blabla database leak&#8220;.</p>



<p>Taking the data protection considered things apart, there&#8217;s one more point being horrific here: &#8222;What the F – who has my password now &#x1f62d;?&#8220;. Well, if done right – means with a proper hashing algorithm – nobody will have your password. Nobody will therefore be able to easily login with your leaked email and password in for example PayPal.</p>



<h3 class="wp-block-heading">Conclusion</h3>



<p>In my opinion, the core concept of using hashes is providing additional value in security based contexts. The three core attributes of a hash are basically: &#8222;It works in one way only&#8220;, &#8222;The output length is fixed&#8220; and &#8222;the source is unknown&#8220;. This beautifully adds more security when storing userdata inside your database like a password or something a pin code, because if someone steals it, they won&#8217;t be able to use it.</p>



<h2 class="wp-block-heading">Does that mean hashing is encryption? Be careful when using MD5 nowadays!</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/Hashing-unequal-encryption.png"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/07/Hashing-unequal-encryption.png" alt="" class="wp-image-10903"/></a><figcaption class="wp-element-caption">Hashing is not encryption! C# MD5 hashing</figcaption></figure>



<p>Oh lord, this is one of the basic misconceptions when talking with some unexperienced developers for sure. Many people still think, that hashing actually means encrypting something. Especially as a freelance developer and therefore seeing so many different developers and companies, I made some experiences in this direction. To quickly say it beforehand: Hashing is not encrypting &amp; decrypting.</p>



<p>When taking a look at one basic argument you will quickly find out why, again, remember my argument: &#8222;Hashing only goes in one direction&#8220;. But if you now think about encryption, there is some input being encrypted and there is a possibility to legimately decode it back.</p>



<h3 class="wp-block-heading">A dangerous problem especially with MD5 – collisions</h3>



<p>If you have spend quite some years in the world of programming, you may already have heard of it: MD5 isn&#8217;t considered cryptographically secure anymore. Honestly I don&#8217;t know how long out of my head at the moment, but it has already been some years. Just a few days ago, I saw one of my tunesian customers actually still using the Message Digest Algorithm 5 (through freelancers work).</p>



<p>I personally think, that you can actually use MD5 in some cases, but please (for god&#8217;s sake), please avoid it considering security based contexts. Another problem next to collisions is MD5 being to fast which enables too easy guessing.</p>



<h2 class="wp-block-heading">Adding more security using salts</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/Salting-hashes.png"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/07/Salting-hashes.png" alt="" class="wp-image-10940"/></a><figcaption class="wp-element-caption">Adding salts into hash computing processes – C# MD5 hashing</figcaption></figure>



<p>Being around in the world of programming you might have already heard of a thing called a &#8222;salt&#8220;. If so, this would actually pretty good, because it&#8217;s one additional gotcha considering security aspects. Think about your hash being a nice food being cooked. Adding a yummy bit of salt you could actually improve the taste of your food (being the hash algorithm).</p>



<p>After hearing that metaphor from above, you can basically say that hashes are &#8222;something being added&#8220; to the source input being hashed. One nice aspect is, that if two users choose the same password, you won&#8217;t be able to see it. Otherwise you could kinda guess by &#8222;Oh, those users have the same hash&#8220;.</p>



<p>Even though I pretty much love rainbows, there is one additional thing, where salted hashes can help against as well. I&#8217;m talking about the common hacking method called / using &#8222;rainbow tables&#8220;. A rainbow table is a premade table of hashed values, where you can try matching records. The future me will eventually go a bit deeper into that, for now that&#8217;s enough to know here.</p>



<h3 class="wp-block-heading">Got the salt – and now?</h3>



<p>When first learning about salts, I can guarantee you, that you are totally not alone with that question. If you have successfully generated your random salt, you will ask yourself: &#8222;Nice, but how am I supposed to let it come into play on the next login attempt?&#8220;. Let me tell you, that you can just store the salt alongside in the database, this way you can use it on login check.</p>



<h2 class="wp-block-heading">What about file hashes?</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/File-hashes.png"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/07/File-hashes.png" alt="Creating hashes from files" class="wp-image-10966" title="Creating hashes from files"/></a><figcaption class="wp-element-caption">Creating hashes from files</figcaption></figure>



<p>Me – at the time of writing this post being 30 – I still enjoy playing games, on PC and as well and consoles. If you have a similar bias, then you will most likey came across some site advertising downloads of games, etc. Sometimes there is a hash being displayed on this download page – for the corresponding download.</p>



<p>When downloading files, there are some things that can go wrong or even revealing themselves as a security problem. Sure there can be less and more problematic things, but think of getting not the actual game client / rom you wanted? You basically enter your login details which then could be send to the malicious producer of this software – while you are still thinking: &#8222;Yes, I got the right game&#8220;.</p>



<h3 class="wp-block-heading">Don&#8217;t trust, validate!</h3>



<p>This basic rule went deep into many persons brains, when the bitcoin slowly settled into peoples memory. It is actually a great saying, which essentially explains, what these file hashes are all about. With those, I – as a manufacturer / developer can tell you the follwing. &#8222;This is the original and correct state of the software I&#8217;m providing to you&#8220;.</p>



<p>After downloading my software or game, you could create a hash to check the file yourself. This would make sure, that you actually got the right one. This ensures that no corruption has happended during the download due to like an instable connection. But most importantly this means: No sneaky hacker has given you a little trojan which he could use to spy on your actitivies and credentials with. This is especially essential when downloading your software through some sort of sharing network.</p>



<h3 class="wp-block-heading">Modifying your favourite game</h3>



<p>Another example could be like one of your favourite nostalgic games put into a ROM. Some developer might brought the game back to life by making a nice mod for it. To actually install that ROM, the developers patching program mostly needs the same starting point. Therefore a hash could express: &#8222;This is the exact version my patcher needs&#8220;.</p>



<h2 class="wp-block-heading" id="quick-examples">Quick examples – C# MD5 hashing</h2>



<p>So, if you have no time for more blabla, then just take a look at those quick examples on &#8222;how to create an MD5 hash in C#&#8220;. Finally I can stop talking and start coding for you, haha &#x1f913;!</p>



<h3 class="wp-block-heading">The older but still OK-working way</h3>



<p>In the first step, we create an instance by the MD5 classes create factory method. Then we are getting the bytes of the actual text by calling GetBytes on our desired encoding. After that, we are computing the actual hash bytes and store them into the corresponding variable. Then, we create a basic <strong><a href="https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder?view=net-6.0" target="_blank" rel="noreferrer noopener">StringBuilder</a></strong> to save up on resources building the final string. In the last step, we are adding the hex representation of each byte to the stringbuilder with the format being &#8222;x2&#8220;. This version should work somewhere up to .NET 4.8, something like that.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    public static string MD5(string clearText)
    {
        using var md5 = System.Security.Cryptography.MD5.Create();
        var bytes = System.Text.Encoding.UTF8.GetBytes(clearText);
        var hash = md5.ComputeHash(bytes);
        var sb = new System.Text.StringBuilder();
        foreach (var byt in hash)
            sb.Append(byt.ToString("x2"));
        return sb.ToString();
    }</pre>



<h3 class="wp-block-heading">The newer version</h3>



<p>In this version we can actually use the factory method of the HashAlgorithm base class, dynamically creating our hash algorithm instance. Then we can also avoid using a stringbuilder, because the Convert class just has a method we can use now. Keep in mind that I&#8217;m expecting &#8222;algo&#8220; not to be null, therefore the &#8222;!&#8220;.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    public static string MD5(string clearText)
    {
        var sb = new StringBuilder();
        var bytes = Encoding.UTF8.GetBytes(clearText);
        using var algo = HashAlgorithm.Create(nameof(MD5));
        var hash = algo!.ComputeHash(bytes);
        return Convert.ToHexString(hash);
    }</pre>



<h3 class="wp-block-heading">Hashing a whole file – the last example</h3>



<p>In this last example I will show you, how you can create a C# MD5 hash from an actual file. Watch out, in this example I&#8217;m not using the &#8222;nameof&#8220; expression, cause the name of the function changed.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    public static string MD5FileHash(string filePath)
    {
        var algo = HashAlgorithm.Create("MD5");
        using var filestream = new FileStream(filePath, FileMode.Open);
        // should be zero by default anyways..
        // filestream.Position = 0;
        var hashValue = algo.ComputeHash(filestream);
        var hash = BitConverter.ToString(hashValue).Replace("-", "");
        return hash;
    }</pre>



<h2 class="wp-block-heading">Related posts</h2>



<ul class="wp-block-list">
<li><strong><a href="https://robbelroot.de/blog/csharp-bluetooth-example-searching-listing-devices/" target="_blank" rel="noreferrer noopener">C# Bluetooth example – listing devices</a></strong></li>



<li><strong><a href="https://robbelroot.de/blog/csharp-sha256-hashing-in-2022/" target="_blank" rel="noreferrer noopener">Creating a C# SHA256 hash</a></strong></li>



<li><strong><a href="https://robbelroot.de/blog/hacking-a-net-application/" target="_blank" rel="noreferrer noopener">Hacking a NET application</a></strong></li>
</ul>
<p>Der Beitrag <a href="https://robbelroot.de/blog/creating-a-csharp-md5-hash/">C# MD5 hashing in 2024</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/creating-a-csharp-md5-hash/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>C# SHA256 hashing in 2024</title>
		<link>https://robbelroot.de/blog/csharp-sha256-hashing/</link>
					<comments>https://robbelroot.de/blog/csharp-sha256-hashing/#comments</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Fri, 15 Jul 2022 06:33:16 +0000</pubDate>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C# HowTo's]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[c sharp]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[create]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[en]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[hash]]></category>
		<category><![CDATA[hashing]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[login]]></category>
		<category><![CDATA[object]]></category>
		<category><![CDATA[salt]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[unhash]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=10777</guid>

					<description><![CDATA[<p>Creating a C# SHA256 hash Creating a C# SHA256 hash as changed a little bit – pardon me for not knowing the exact timestamp though. At least this is the thing I&#8217;ve stumbled upon a few days ago, when I needed it in my customer project. So, in today&#8217;s post &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/csharp-sha256-hashing/">C# SHA256 hashing in 2024</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/C-SHA256-Hashing.png"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/07/C-SHA256-Hashing.png" alt="C# SHA256 Hashing" class="wp-image-10859" title="C# SHA256 Hashing"/></a><figcaption class="wp-element-caption">C# SHA256 Hashing</figcaption></figure>






<h2 class="wp-block-heading">Creating a C# SHA256 hash</h2>



<p>Creating a C# SHA256 hash as changed a little bit – pardon me for not knowing the exact timestamp though. At least this is the thing I&#8217;ve stumbled upon a few days ago, when I needed it in my customer project. So, in today&#8217;s post we will talk about the essential basics of hashing and how to create a SHA256 hash in the context the C# language. By the way – we won&#8217;t use any third party library here.</p>



<p class="info-banner">&#x1f4a1; No time for blabla? No problem! If you prefer quick code snippets on creating C# SHA256 hashes, just go to <strong><a href="#quick-examples">the quick examples section</a></strong>.</p>



<style>
.info-banner {
  background: #8acc47;
  padding: 2em;
  border-radius: 0.5em;
  color: whitesmoke;
}

.info-banner a {
 color: #2E86AB !important; 
}
</style>



<h2 class="wp-block-heading">Some basics about &#8222;data&#8220;?</h2>



<p>If we want to find out what hashes actually are, we first need to step back a moment, to see how data is stored. In the first example we could start with a simple string like &#8222;MyPassword123&#8220; (no I won&#8217;t use Hello World &#x1f92e;). After seeing hundreds of bad passwords, I want to explicitely call out: &#8222;Don&#8217;t use such a bad password&#8220; – just sayin&#8216;.</p>



<h3 class="wp-block-heading">Data basics</h3>



<p>So when talking about &#8222;data&#8220; in general – while being in a computational context –, we actually talk about something called &#8222;bytes&#8220;. In its singular form – a &#8222;byte&#8220; – it&#8217;s the smallest addressable unit of memory inside a modern computer. Diving even deeper, a byte consists of 8 bits, that are basically &#8222;connected&#8220; together. Take a look at the following illustration:</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/C-SHA256-Hashing-The-basics-about-bytes-and-data.png"><img loading="lazy" decoding="async" width="555" height="300" src="https://robbelroot.de/wp-content/uploads/2022/07/C-SHA256-Hashing-The-basics-about-bytes-and-data.png" alt="C# SHA256 Hashing - The basics about bytes and data" class="wp-image-10804" title="C# SHA256 Hashing - The basics about bytes and data"/></a><figcaption class="wp-element-caption">C# SHA256 Hashing &#8211; The basics about bytes and data</figcaption></figure>



<p>So as you can see in the image, there are 8 – more or less – independent bits, still acting together as one byte. Each one of these bits, can be in one of two states: Either on, or off. Depending on those on/off states, the byte changes it&#8217;s representing value. This is why it&#8217;s called binary – either, your computer works, or it doesn&#8217;t #clownoff &#x1f609;! Next, we are going to look at some concrete data examples.</p>



<h3 class="wp-block-heading">Example data</h3>



<p>Please understand, that I won&#8217;t go into this too deep, but I think some basic examples are required to at least have some basic knowledge. Of course you can skip this section, if this is baby stuff for you &#x1f60b;! Let&#8217;s take a look at two examples now: One number, and one string.</p>



<h4 class="wp-block-heading">A number – let&#8217;s say 42</h4>



<p>Let&#8217;s now take a look at some basic number being represented by those bits inside the byte, for example &#8222;42&#8220;. After taking that sneak peek, I will explain it in more detail.</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/A-basic-number-being-represented-as-byte.png"><img loading="lazy" decoding="async" width="489" height="171" src="https://robbelroot.de/wp-content/uploads/2022/07/A-basic-number-being-represented-as-byte.png" alt="A basic number being represented as byte" class="wp-image-10832" title="A basic number being represented as byte"/></a><figcaption class="wp-element-caption">A basic number being represented as byte</figcaption></figure>



<p>So as you can see, the binary representation (in form of a byte) of the number &#8222;42&#8220; is basically &#8222;00101010&#8220;. As I&#8217;ve already mentioned, each one of those bytes can either be &#8222;on&#8220;, or &#8222;off&#8220;. This is represented by the corresponding numbers being &#8222;0&#8220; for &#8222;off&#8220; and &#8222;1&#8220; for &#8222;on&#8220;.</p>



<p>With my (german biased) english wording skills, I would explain it like this:</p>



<p>Each one of the single digits represent a &#8222;value&#8220; being doubled after each step. Important note: You start on the right side, with the value &#8222;1&#8220;. Then you basically look at each byte (again, from the right side) and remember the active values:</p>



<ul class="wp-block-list">
<li>The &#8222;1&#8220; bit -&gt; is off, so don&#8217;t take it into account = 0</li>



<li>The &#8222;2&#8220; bit -&gt; it&#8217;s on, take its value = 2</li>



<li>The &#8222;4&#8220; bit is off, ignore..</li>



<li>The &#8222;8&#8220; bit is on, take it!</li>
</ul>



<p>So, if we continue like this we will have the following active values at the end: 2, 8 and 32. Now guess what this makes up, if we sum it together – correct, 42 &#x1f389;!</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/How-does-a-byte-represent-its-outer-value-C-Hash-basics.png"><img loading="lazy" decoding="async" width="828" height="369" src="https://robbelroot.de/wp-content/uploads/2022/07/How-does-a-byte-represent-its-outer-value-C-Hash-basics.png" alt="How does a byte represent its outer value - C# Hash basics" class="wp-image-10838" title="How does a byte represent its outer value - C# Hash basics"/></a><figcaption class="wp-element-caption">How does a byte represent its outer value &#8211; C# Hash basics</figcaption></figure>



<h4 class="wp-block-heading">A string being &#8222;MyPassword123&#8220;</h4>



<p>After taking a look at this rather easy and basic &#8222;number only&#8220; example, we will now go ahead and check out the mentioned string &#8222;MyPassword123&#8220;. Allthough strings being more complex, they are basically following the same rules. Being a Zelda fan since good old kiddie-times – therefore loving to open chests – I don&#8217;t like opening another one here.</p>



<p>I&#8217;m talking about a topic called character encodings – seriously, I will take a shortcute here. For now, just keep in mind, that we are using the basic <strong><a href="https://en.wikipedia.org/wiki/ASCII" target="_blank" rel="noreferrer noopener">ASCII table</a></strong> for &#8222;decoding&#8220; our letters. Let&#8217;s now go ahead and start decoding our string beginning with the character &#8222;M&#8220;.</p>



<p>Taking a look at the ASCII table – mentioned and linked above – we can see, that the big &#8222;M&#8220; has an ASCII value / code of &#8222;077&#8220;. You can even try typing that code manually by using your numpad on the left (if you have one). Hold the &#8222;alt&#8220; key and type the code: &#8222;077&#8220;, after releasing &#8222;alt&#8220; then, you should notice an appeared &#8222;M&#8220; letter &#x1f60e;.</p>



<h4 class="wp-block-heading">What is M&#8217;s binary representation?</h4>



<p>Now let&#8217;s find out how the letter &#8222;M&#8220; is represented in a binary form – having the info it&#8217;s ASCII code is &#8222;077&#8220;. Take a look how the number 77 would be displayed in a bitwise manner:</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/The-number-42-represented-bitwise-C-SHA256.png"><img loading="lazy" decoding="async" width="585" height="224" src="https://robbelroot.de/wp-content/uploads/2022/07/The-number-42-represented-bitwise-C-SHA256.png" alt="The number 77 represented bitwise - C# SHA256" class="wp-image-10870" title="The number 77 represented bitwise - C# SHA256"/></a><figcaption class="wp-element-caption">The number 77 represented bitwise &#8211; C# SHA256</figcaption></figure>



<p>Now we can just repeat the algorithm already explained a few steps above. Start from the right side, with value 1. Double it&#8217;s value 7 times – which get&#8217;s you to the final &#8222;128&#8220; value. Then check whether the bit is &#8222;active&#8220; and take its value into the sum:</p>



<ul class="wp-block-list">
<li>Bit 1 -&gt; checked = 1</li>



<li>Bit 3 -&gt; checked = 4</li>



<li>Bit 4 -&gt; checked = 8</li>



<li>Bit 7 -&gt; checked = 64</li>
</ul>



<p>Summing it up alltogether, we now have our target value, which is &#8222;77&#8220;. I will save your time repeating it for each and every other letter inside our target string &#x1f601;! If you still want to see the whole binary representation of our string, here it comes:</p>



<pre class="wp-block-code"><code>01001101 01111001 01010000 01100001 01110011 01110011 01110111 01101111 01110010 01100100 00110001 00110010 00110011</code></pre>



<h2 class="wp-block-heading">What is a hash in the first place?</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/Is-this-a-SHA256-hash-meme.png"><img loading="lazy" decoding="async" width="700" height="420" src="https://robbelroot.de/wp-content/uploads/2022/07/Is-this-a-SHA256-hash-meme.png" alt="Is this a SHA256 hash meme" class="wp-image-10895" title="Is this a SHA256 hash meme"/></a><figcaption class="wp-element-caption">Is this a SHA256 hash meme</figcaption></figure>



<p>After taking a look into the basics of storing data inside the computers memory, we can now go a bit further (pun intended). I think the most basic explanation goes like this: &#8222;You provide some value, apply some algorithm to it and get an output value&#8220;. One more thing to mention is: &#8222;The same input will result in the same output&#8220;.</p>



<p>Before we continue with blabla &#x1f605;, I would like to show you like 3 examples:</p>



<ul class="wp-block-list">
<li>ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb</li>



<li>bc7b8851671f2fda237a53f5057a0376037b6d062e65f965c62aa1d047498759</li>



<li>befc3e74171cfac5f713b41512ded54cee67aa10aec174659f99ac19fb2f2974</li>
</ul>



<h3 class="wp-block-heading">First important point – &#8222;unknown&#8220; source</h3>



<p>Pretty much nonsense, huh? But well, not really, actually you know at least two of those thing. Here you can already see one of the important points of hashing. Using hashes basically hides the origin, so you don&#8217;t really know the &#8222;source&#8220; of the hash. Further down, we will explore why / when this could be really helpful.</p>



<h3 class="wp-block-heading">Fixed output length – the second point</h3>



<p>The first hash from above is – surprisingly – just a small letter called &#8222;a&#8220;, weird – right!? The second one is our password string we used as an example from above. Especially the third one is pretty interesting, it&#8217;s actually one of the image files I&#8217;ve used in this post.</p>



<p>A SHA256 hash is 256 bits long – always – and it is being represented using hexadecimal notation. As the hexadecimal notation is only in the need of 4 bits for each character, you can actually have 256 / 4 = 64 characters. Therefore you could for example store it with a char(64) field inside a typical mySQL database.</p>



<h3 class="wp-block-heading">Third point – it&#8217;s a one-way train</h3>



<p>The third and another important point is, that a hash is actually irreversible, once you go forwards, you can&#8217;t go back. It might sound, or like a disadvantage, but it can be a real benefit in some situations. We will dive deeper into the &#8222;where is it good&#8220; or &#8222;why&#8220; in a few seconds.</p>



<h2 class="wp-block-heading">Why do I need to hash &#8222;things&#8220;?</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/C-SHA256-Why-you-should-hash.png"><img loading="lazy" decoding="async" width="640" height="360" src="https://robbelroot.de/wp-content/uploads/2022/07/C-SHA256-Why-you-should-hash.png" alt="C# SHA256 - Why you should hash" class="wp-image-10864" title="C# SHA256 - Why you should hash"/></a><figcaption class="wp-element-caption">C# SHA256 &#8211; Why you should hash</figcaption></figure>



<p>Well, after seeing all these basics and stuff, you could ask yourself: &#8222;But why is hashing used at all?&#8220;. For sure this is a really good question. There&#8217;s one special use case, which comes into my mind pretty fast.</p>



<h3 class="wp-block-heading">Users, Login and stuff</h3>



<p>The first use case I got strictly paired with hashing in my mind is something what almost every app needs: A login / authentication of a user. We all used it hundreds of times a login screen, but how does it actually work in the background?</p>



<p>When a user confirms his entered credentials like &#8222;robert&#8220; as username and &#8222;MyPassword123&#8220;, it gets send to the server side of our app. Then the server app will go ahead and try to pull the matching user record for the specified username. If it has not been able to find a matching username record, well then we usually get a corresponding error.</p>



<h3 class="wp-block-heading">Hashing comes into play</h3>



<p>The interesting part happens next, when the user could actually be found using the provided username. Then the controlling part will mostly try to hash the entered password with the configured hash algorithm. Having the hashed user password in the hand, it will compare the hashed password with the password from the database – which is stored as hash as well.</p>



<p>If you remember that one important point where I said that &#8222;hashes are irreversible&#8220;, then this is, where the actual power is here. I think everyone has heard of that typical &#8222;breaking IT news&#8220;, that someones database got stolen. There are similar news where the headlines are like &#8222;xy thousand user datasets&#8220; has been leaked.</p>



<p>Now imagine what would happen if you could just read everyones password in clear text like: &#8222;Oh yeah, Robert&#8217;s password is like &#8218;MyPassword123&#8242;&#8220;. Someone could try to use this password in the same application or in other important apps like PayPal. I mean there are many persons using their email as login ident, so.. And with that databases getting leaked, you have them anyways – hacky-boy jackpot.</p>



<h3 class="wp-block-heading">Conclusion</h3>



<p>So the primary aspect of hashing has its roots – in my opinion – in the context of security. The 3 core aspects of hashes are: &#8222;Being one way only&#8220;, &#8222;Having a fixed length&#8220; and most important &#8222;The source is unknown&#8220;. That enables storing and comparing passwords, pins, etc. in a secured matter making it less critical if they get leaked.</p>



<h2 class="wp-block-heading">So hashing means encrypting – no?</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/Hashing-unequal-encryption.png"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/07/Hashing-unequal-encryption.png" alt="Hashing unequal encryption" class="wp-image-10903" title="Hashing unequal encryption"/></a><figcaption class="wp-element-caption">Hashing unequal encryption</figcaption></figure>



<p>Well this is one of the most common misconceptions, even in more advanced developer circles. I came across wordings like &#8222;yeah, let&#8217;s encrypt it with SHA256&#8220; in my business context more often than you might think. You should remember one thing: Hashing isn&#8217;t encrypting &amp; decrypting.</p>



<p>As I already mentioned above, hashing only goes in one direction: You input something, it does its magical mathematical work and in the hand you have your output. Encryption means something different, it indicates that you are able to encode something and decode it back again.</p>



<h3 class="wp-block-heading">But what is the catch – talking about collisions</h3>



<p>If you are already in the universe of programming for some time, you might have heard of some hashing algorithm called &#8222;MD5&#8220;. Just a few days ago, when I worked for a tunesian customer, the Message-Digest Algorithm 5 was actually being used. Considering the security context, let me tell you one thing: Don&#8217;t use it in a problematic context nowadays!</p>



<p>When I was talking about &#8222;hashes are irreversible&#8220;, then that was actually the – more or less – full truth. But there is one thing called &#8222;collisions&#8220; which can occur, when using bad / outdated hashing algorithms. The Message-Digest Algorithm 5 is one of those you should therefore avoid.</p>



<h2 class="wp-block-heading">Salts – The right seasoning?</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/Salting-hashes.png"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/07/Salting-hashes.png" alt="Salting hashes" class="wp-image-10940" title="Salting hashes"/></a><figcaption class="wp-element-caption">Salting hashes</figcaption></figure>



<p>You might have heard about a thing called &#8222;salt / salts&#8220; in the context of hashing algorithms. Actually it is pretty good if so, because it&#8217;s an additional thing for more security. If you think of your hash algorithm being some kind of dinner being cooked, then a salt can add more flavour to your algo.</p>



<h3 class="wp-block-heading">How does it theoretically work?</h3>



<p>Salting is &#8222;something additional&#8220; being added to the password before being stored into the database. This will ensure, that even if two users choose the same password, the hashed output will still be different. If some user gets hacked you can&#8217;t guess like &#8222;ah, this other user has the same hash, therefore he has the same password&#8220;.</p>



<p>Another nice security thing about salts is adding protection against the rainbow table hacking method. A rainbow table attack is basically a hacking attempt, where you have some kind of premade / precached table of hashed values. Maybe this is a topic for another post, I think this one is already long enough &#x1f602;.</p>



<h3 class="wp-block-heading">But where does the salt go?</h3>



<p>This is a question I (any many more guys) have asked myself when I first got in contact with salting hashes. I though like: &#8222;Well, if I randomly and uniquely generate that salt on like registration, how am I supposed to ever find it back?&#8220;. Adding to this: &#8222;And how am I then to ever be able to check the password on a login attempt?&#8220;.</p>



<p>The answer is pretty easy: You just store the salt alongside with the password inside the database.</p>



<h2 class="wp-block-heading">I&#8217;ve seen file hashes as well?</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2022/07/File-hashes.png"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2022/07/File-hashes.png" alt="File hashes" class="wp-image-10966" title="File hashes"/></a><figcaption class="wp-element-caption">File hashes</figcaption></figure>



<p>As a passionate hobby-gamer (yes, even with 30 and will be with 80) I have seen those many times as well. Those little &#8222;hey, this file has a hash of xyz&#8220; hints, mostly located at some download pages. And here its a security aspect as well, who would&#8217;ve thought that, huh!?</p>



<p>When downloading files, there are some things that can go wrong or even revealing themselves as a security problem. Sure there can be less and more problematic things, but think of getting not the actual game client / rom you wanted? You basically enter your login details which then could be send to the malicious producer of this software – while you are still thinking: &#8222;Yes, I got the right game&#8220;.</p>



<h3 class="wp-block-heading">Don&#8217;t trust, validate!</h3>



<p>So there is this nice basic rule which settled in many minds when the bitcoin first came into peoples memory: &#8222;Don&#8217;t trust, validate!&#8220;. This is actually one great thing, which essentially explains, what these file hashes are all about. The official vendor can tell you like &#8222;This is the original and correct state of the software I&#8217;m providing to you&#8220;.</p>



<p>After downloading the software you could create the hashed version of the file yourself making sure, that you actually got the right one. This means: No corruption has happended during download and everything should be working fine. And this also means: No sneaky hacker has given you a little trojan which he could use to spy on your actitivies and credentials with. This is especially essential when downloading your software through some sort of sharing network.</p>



<h3 class="wp-block-heading">Patching your favourite game</h3>



<p>Another example is for example when you have some old ROM for your favourite nostalgia game. There could be some developer, who made a nice romhack (extending / changing the original for more fun). He would most likely need the same origin / starting point of a software, being able to patch it exactly like he needs to.</p>



<h2 class="wp-block-heading" id="quick-examples">Quick examples – C# SHA256 hashing</h2>



<p>No time for blabla? Just take a look at the different quick examples listed below. Finally I can write some code for you to create some C# SHA256 hash &#x1f913;!</p>



<h3 class="wp-block-heading">The old, outdated way</h3>



<p>In the outdated version (where the SHA256Managed class even get&#8217;s marked by Visual Studio) we have a basic <strong><a href="https://docs.microsoft.com/en-us/dotnet/api/system.text.stringbuilder?view=net-6.0" target="_blank" rel="noreferrer noopener">StringBuilder</a></strong>. Then we create an instance of the hash algorithm with the factory method called &#8222;create&#8220;. Take care for me using the newer &#8222;using&#8220;-syntax in one line = without curly braces.</p>



<p>Next we are getting the UTF8 bytes of the &#8222;clearText&#8220; string variable and passing them to the &#8222;ComputeHash&#8220; function of our hash algorithm class instance. Then we are iterating the byte array called result formatting each one into its hex representation. At the end, we are finally returning the hashed string.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">public static string SHA256Outdated(string clearText)
{
  var sb = new StringBuilder();
  using var hash = SHA256Managed.Create();
  var result = hash.ComputeHash(Encoding.UTF8.GetBytes(clearText));
  foreach (var b in result)
    sb.Append($"{b:x2}");
  return sb.ToString();
}</pre>



<h3 class="wp-block-heading">The new version</h3>



<p>The newer version works similar to the above one, except that we are using the &#8222;create&#8220; factory method of the &#8222;HashAlgorithm&#8220; class. There we provide the name of the hash algorithm we want to use. I love using the &#8222;nameof&#8220; expression, but feel free to just provide &#8222;SHA256&#8220; as string. Next we are doing pretty much the same as above as well.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">using System.Text;
using System.Security.Cryptography;

private static string SHA256(string clearText)
{
  var sb = new StringBuilder();
  var bytes = Encoding.UTF8.GetBytes(clearText);
  var algo = HashAlgorithm.Create(nameof(SHA256));
  var hash = algo!.ComputeHash(bytes);
  foreach (var byt in hash)
    sb.Append(byt.ToString("x2"));
  return sb.ToString();
}</pre>



<h3 class="wp-block-heading">Hashing a file</h3>



<p>This is an example of hashing an actual file like we have talked about further above.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    public static string SHA256FileHash(string filePath)
    {
        var algo = HashAlgorithm.Create("SHA256");
        using var filestream = new FileStream(filePath, FileMode.Open);
        // should be zero by default anyways..
        // filestream.Position = 0;
        var hashValue = algo.ComputeHash(filestream);
        var hash = BitConverter.ToString(hashValue).Replace("-", "");
        return hash;
    }</pre>



<h2 class="wp-block-heading">++ .NET 5 Update – Static Algorithm Methods ++</h2>



<p>So a user just commented like &#8222;this is wrong&#8220;, well okay, what a neat description / criticism.. I thought I should write an update, with my thought process about this. I&#8217;m pretty open for any based criticism and arguments, so go ahead, if you have other suggestions.</p>



<p>The back story of his argument could be: In the &#8222;code analysis&#8220; – id &#8222;<strong><a href="https://learn.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca1850" target="_blank" rel="noreferrer noopener">CA1850</a></strong>&#8220; – there is written, that you should actually use the static methods of the corresponding hash algorithm, called &#8222;<strong><a href="https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata?view=net-7.0" target="_blank" rel="noreferrer noopener">HashData</a></strong>&#8222;. As there&#8217;s written, those are only aliases to the static methods, so you basically can avoid instantiating an algorithm each time. But who says you need to?</p>



<p>In my opinion I want to be able to switch out different hash algorithms as easy as possible. Further, I would do this by just injecting the right algorithm instance by dependency injection – once. Like this, I can mantain a nice, loosely coupled infrastructure and I&#8217;m not over-creating instances.</p>



<p>Just my opinion: So, in the end, you can decide yourself, if you want to listen to the code analysis CA1850, or if you just want to like use DI and inject an actual instance of a hash algorithm. On the other hand, if &#8222;switching out&#8220; isn&#8217;t necessary for you – like when you always need one specific algorithm, always – you can just go with the static methods.</p>



<h2 class="wp-block-heading">Related posts</h2>



<ul class="wp-block-list">
<li><strong><a href="https://robbelroot.de/blog/csharp-bluetooth-example-searching-listing-devices/" target="_blank" rel="noreferrer noopener">C# Bluetooth example – Listing devices</a></strong></li>



<li><strong><a href="https://robbelroot.de/blog/csharp-for-each-iterating-the-objective-way/" target="_blank" rel="noreferrer noopener">The For Each Loop in C# – Objective iteration</a></strong></li>
</ul>
<p>Der Beitrag <a href="https://robbelroot.de/blog/csharp-sha256-hashing/">C# SHA256 hashing in 2024</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/csharp-sha256-hashing/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>VB NET Formular automatisch ausfüllen (Winforms)</title>
		<link>https://robbelroot.de/blog/vbnet-formular-automatisch-ausfuellen-winforms/</link>
					<comments>https://robbelroot.de/blog/vbnet-formular-automatisch-ausfuellen-winforms/#comments</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Wed, 15 Dec 2021 17:40:57 +0000</pubDate>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Visual Basic .NET]]></category>
		<category><![CDATA[Visual Basic .NET Problemlösungen]]></category>
		<category><![CDATA[ausfüllen]]></category>
		<category><![CDATA[automation]]></category>
		<category><![CDATA[automatisch]]></category>
		<category><![CDATA[automatisiert]]></category>
		<category><![CDATA[automatisierung]]></category>
		<category><![CDATA[complete]]></category>
		<category><![CDATA[fill]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[formular]]></category>
		<category><![CDATA[kompletieren]]></category>
		<category><![CDATA[set]]></category>
		<category><![CDATA[setzen]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[text]]></category>
		<category><![CDATA[textbox]]></category>
		<category><![CDATA[texte]]></category>
		<category><![CDATA[vb.net]]></category>
		<category><![CDATA[vbnet]]></category>
		<category><![CDATA[vervollständigen]]></category>
		<category><![CDATA[windows]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=6744</guid>

					<description><![CDATA[<p>VB.NET Formulare automatisch ausfüllen! Ein VB NET Formular automatisch ausfüllen zu lassen wäre vermutlich für jeden &#8222;Windows Forms&#8220; geprägten Entwickler eine Erleichterung. Man designt die Form seiner Wahl und möchte natürlich bei Aufruf die notwendigen Daten anzeigen. Besonders beim Flow aus diversen Suchmasken heraus ist es normal, dass man eine &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vbnet-formular-automatisch-ausfuellen-winforms/">VB NET Formular automatisch ausfüllen (Winforms)</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2021/12/VB.NET-Formular-automatisch-ausfuellen.png"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2021/12/VB.NET-Formular-automatisch-ausfuellen.png" alt="VB.NET Form automatisch ausfüllen" class="wp-image-6747" title="VB.NET Form automatisch ausfüllen"/></a><figcaption>VB.NET Form automatisch ausfüllen</figcaption></figure>






<h2 class="wp-block-heading">VB.NET Formulare automatisch ausfüllen!</h2>



<p>Ein <strong>VB NET Formular automatisch ausfüllen zu lassen</strong> wäre vermutlich für jeden &#8222;Windows Forms&#8220; geprägten Entwickler eine Erleichterung. Man designt die Form seiner Wahl und möchte natürlich bei Aufruf die notwendigen Daten anzeigen. Besonders beim Flow aus diversen Suchmasken heraus ist es normal, dass man eine Detail-Ansicht mit entsprechenden Daten aufruft.</p>



<h3 class="wp-block-heading">Wie es meistens ist..</h3>



<p>Am besten wäre es natürlich, wenn man dem Formular direkt sagen könnte: &#8222;Hey, die Daten findest Du dort&#8220;. Mit modernen Mitteln wie in der WPF (Windows Presentation Foundation) ist dies durch Datenbindung eine gängige und vor allem einfache Praxis.</p>



<p>Dort findet man durch die saubere Trennung zwischen GUI und Daten eine simple und direkt in XAML implementierte Möglichkeit. In den guten alten Winforms findet man jedoch seltenst (jedenfalls aus meiner Erfahrung gesprochen) datengebundene Steuerelemente.</p>



<h3 class="wp-block-heading">Monkey Work – ney, Automatisierung – yay!</h3>



<p>Dort sieht es dann entgegengesetzt jeglicher Automatisierung eher so aus:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">TextBox1.Text = "..."
TextBox2.Text = "..."
TextBox3.Text = "..."
TextBox4.Text = "..."
' ....</pre>



<p>Eventuell entwickelt man wenigstens einigermaßen sauber und wählt passende Namen für die Textboxen:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tbFirstName.Text = "..."
tbLastName.Text = "..."
tbZip.Text = "..."
tbCity.Text = "..."
' ....</pre>



<p>Schon besser, aber natürlich kann man sich schon vorstellen, dass dies nicht unbedingt das Gelbe vom Ei ist. Man wird auf diverse Probleme, bzw. Monkey-Work stoßen, Welche für Wartung und Co. nicht gerade vorteilhaft sind. Tonnenweise &#8222;duplicated Code&#8220; und schon glatt eine Qual, wenn es bei einem Objekt mit 30 Properties heißt: &#8222;Hey, zeige die Daten mal an&#8230;&#8220;.</p>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2021/12/VB.NET-Formulare-ausfuellen-Monkey-Work.png"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2021/12/VB.NET-Formulare-ausfuellen-Monkey-Work.png" alt="VB.NET Formulare ausfüllen Monkey Work" class="wp-image-6750" title="VB.NET Formulare ausfüllen Monkey Work"/></a><figcaption>VB.NET Formulare ausfüllen Monkey Work</figcaption></figure>



<p>Nun ist man an einem Punkt, wo die bekannte Faulheit doch zum Vorteil sein und zu mehr Effizienz beitragen kann. Wie so häufig, haben wir als Entwickler die Möglichkeit uns gewisse (und vor allem wiederkehrende Aufgaben) zu vereinfachen. Not macht erfinderisch, richtig?</p>



<h3 class="wp-block-heading">An die Zukunft denken</h3>



<p>Je nachdem wie viel Planung und anschließenden Zeitaufwand man bereit ist zu investieren (nicht opfern!), wird die bevorstehende Arbeit beeinflussen. Man sollte meiner Meinung nach jedoch immer eins im Hinterkopf behalten: &#8222;Think twice, code once&#8220;! Leider arbeiten viele Entwickler auch gerne nach dem &#8222;Copy &amp; Paste&#8220;-Prinzip, zur Not auch projektübergreifend.</p>



<p>Statt hier zukunftsorientiert zu denken, werden Aufgaben häufig nur akut und schnell gelöst. Auch wenn die Erledigung einiger Aufgaben ggf. am Anfang nervig und zeitaufwendig sind, können Sie einem später unfassbar viel Zeit ersparen. Dies gilt natürlich nicht nur für das aktuelle Projekt, sondern vermutlich auch noch für später anstehende Projekte und Problemstellungen.</p>



<h2 class="wp-block-heading">Herangehensweise – VB NET Formular automatisch ausfüllen</h2>



<p>Im nächsten Schritt machen wir uns einmal ein paar Gedanken bezüglich der Herangehensweise, die (Windows Forms)-Formulare automatisiert(er) auszufüllen. Auch wenn wir hier vermutlich noch keine volle Suite an Mini-Tools generieren werden, wird das meinerseits dargestellte Beispiel als Startschuss dienen können.</p>



<p>Jeder Entwickler im NET Bereich wird wohl immer wieder mal mit den guten alten <a href="https://docs.microsoft.com/de-de/dotnet/api/system.windows.forms.textbox?view=windowsdesktop-6.0" target="_blank" rel="noreferrer noopener"><strong>Textboxen</strong></a> zu tun haben. Ich denke, dass dieses Steuerelement daher auch die erste zu bearbeitende Anlaufstelle sein sollte. Wenn man hingegen an <a href="https://docs.microsoft.com/de-de/dotnet/api/system.windows.forms.checkbox?view=windowsdesktop-6.0" target="_blank" rel="noreferrer noopener"><strong>Checkboxen</strong></a>, <a href="https://docs.microsoft.com/de-de/dotnet/api/system.windows.forms.listbox?view=windowsdesktop-6.0" target="_blank" rel="noreferrer noopener"><strong>Listboxen</strong></a> und an die anderen Steuerelemente denkt, könnte es schon ein wenig komplexer werden.</p>



<p>Vielleicht werde ich dafür dann noch einmal einen getrennten Beitrag in Zukunft erstellen. Schauen wir einmal, wo mich die Beitrags-Reise, bzw. meine Schreib-Lust heute hinführt &#x1f609;.</p>



<h3 class="wp-block-heading">Konkreter Ablauf</h3>



<p>Wenn man sauber vorgeht, sollte man die Daten natürlich in irgendeiner sinnvollen Form vorliegen haben. Nach Möglichkeit gibt es hier also nicht z. B. 15 verschiedene Variablen, Welche dann im schlimmsten Fall noch &#8222;string1, string2, usw.&#8220; heißen. Wir wollen ja im besten Fall mit relativ fest definierten Mustern arbeiten, um unsere Arbeit so einfach wie möglich zu gestalten.</p>



<p>Ich stelle mir einerseits eine bereits definierte Klasse als Daten-Container vor, andererseits könnte es sich auch um analog zugreifbare Daten wie bei einer DataRow handeln. Den konkreten Ablauf würde man  kurz und knapp vielleicht so beschreiben: &#8222;Nimm dieses Ding hier und packe dessen Eigenschafts-Werte in die passenden Steuerelemente&#8220;.</p>



<p>Dabei könnte man entweder ausgehend vom Objekt, oder von der jeweiligen Form arbeiten, also Pseudocode mäßig so:</p>



<pre class="wp-block-code"><code>Für jede Eigenschaft im Objekt, finde die passende Textbox, trage den passenden Wert ein..</code></pre>



<p>oder..</p>



<pre class="wp-block-code"><code>Für jede/s Textbox/Steuerelement auf dem Formular, finde im Ziel-Objekt die passende Eigenschaft und befülle Diese.</code></pre>



<p>Eventuell könnte man hier auch noch für die Performance mit irgendeiner Art Cache arbeiten, oder je nach Situation die &#8222;Strategie&#8220; (Anspielung Strategy-Pattern&#8230;) ändern. Ich werde es hier allerdings nicht weiter als nötig verkomplizieren, da dieses Beispiel nur als Inspiration dienen soll.</p>



<h2 class="wp-block-heading">Code – VB NET Formular automatisch ausfüllen</h2>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2021/12/VB.NET-Formular-automatisch-ausfuellen-mit-Kundendaten.png"><img loading="lazy" decoding="async" width="1200" height="628" src="https://robbelroot.de/wp-content/uploads/2021/12/VB.NET-Formular-automatisch-ausfuellen-mit-Kundendaten.png" alt="VB.NET Formular automatisch ausfüllen mit Kundendaten" class="wp-image-6786" title="VB.NET Formular automatisch ausfüllen mit Kundendaten"/></a><figcaption>VB.NET Formular automatisch ausfüllen mit Kundendaten</figcaption></figure>



<p>Nachdem wir die Herangehensweise ein wenig durch Pseudocode dargestellt haben, starten wir auch direkt in den Code. Ich werde auf jeden Fall ein Modul verwenden, damit man den Code auch einfach für andere Projekte wiederverwenden kann. Alternativ könnte man natürlich auch eine getrennte Klassenbibliothek, ein NuGet-Paket, o. Ä. erstellen.</p>



<p>Mit gewissen neuen aus C# bekannten Features könnte man auch vielleicht in Visual Basic eine &#8222;Trait&#8220; ähnelnde Verwendungsweise realisieren. Wie bekannt ist, ist Komposition ja zumeist besser, als Vererbung (Stichwort: &#8222;composition over inheritance&#8220;). &#8222;Traits&#8220; kennt man zum Beispiel allzu gut aus der Web-Programmiersprache namens PHP, aber dazu vielleicht in einem anderen Beitrag mehr.</p>



<h3 class="wp-block-heading">Das Modul</h3>



<p>Erstelle nun im ersten Schritt ein neues Modul namens (z. B.) &#8222;modExtensions&#8220; – auch hier verwende ich gerne eine kleine Konvention. Ich halte mich immer an ähnliche Bezeichnungen / Präfixe, wie z. B. &#8222;tb&#8220; für eine Textbox, &#8222;cbb&#8220; für eine Combobox, etc. Welchen Sinn das dann eventuell haben kann / wird, sehen wir unter anderem (und besonders) im heutigen Beitrag!</p>



<p>Da wir schon analog zum Modul geplant haben, eine <a href="https://docs.microsoft.com/de-de/dotnet/visual-basic/programming-guide/language-features/procedures/extension-methods" target="_blank" rel="noreferrer noopener"><strong>Erweiterungsmethode</strong></a> zu verwenden, importieren wir direkt den &#8222;System.Runtime.CompilerServices&#8220;-Namespace.</p>



<h3 class="wp-block-heading">Eine Fill-Methode – VB NET Formular automatisch ausfüllen</h3>



<p>Durch den Import des zuvor genannten Namespaces, können wir dann das &#8222;Extension&#8220;-Attribut verwenden und unsere Methode namens z. B. &#8222;Fill&#8220; damit bestücken.</p>



<p>Als nächstes definieren wir die beiden benötigten Parameter:</p>



<ul class="wp-block-list"><li>Die <strong>Form</strong>, bzw. dessen Steuerelemente, <strong>Welche befüllt werden sollen</strong></li><li>Das <strong>Objekt</strong>, also eine jeweilige Instanz eines x-beliebigen Typs, <strong>Welches </strong>die <strong>Daten beinhaltet</strong></li></ul>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Imports System.Runtime.CompilerServices

Module modExtensions

    &lt;Extension()>
    Public Sub Fill(frm As Form, obj As Object)
        ' ...
    End Sub

End Module</pre>



<p>Danach erfassen wir die Textboxen aus der &#8222;Controls&#8220;-Auflistung des Formulars, damit wir Diese anschließend verwenden können. Praktisch im gleichen Schritt, ziehen wir uns einfach auch direkt die Eigenschaften (Definitionen) des Daten-Objekts.</p>



<p>Das geht relativ einfach, also wie folgt:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Dim textBoxes = frm.Controls.OfType(Of TextBox)
Dim properties = obj.GetType().GetProperties()</pre>



<p>Danach können wir die eben abgerufenen Textboxen einfach in einer &#8222;For Each&#8220;-Schleife durchlaufen und dann mit dem Befüllen der Eigenschaften beginnen. Im ersten Teil der Schleife prüfen wir, ob die jeweilige Textbox mit dem korrekten Prefix &#8222;tb&#8220; betitelt wurde. Wir halten uns also an eine kleine, von uns festgelegte Konvention. Vielleicht sollte man dies auch durch ein eigenes Attribut konfigurierbar machen, jedoch verzichten wir der Einfachheit halber aktuell darauf. Falls die Textbox nicht mit &#8222;tb&#8220; beginnt, ignorieren wir Sie aktuell einfach, sprich die Schleife springt in den nächsten Durchlauf.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Dim wrongPrefix = Not tb.Name.StartsWith("tb")
If wrongPrefix Then
    Continue For
End If</pre>



<p>Der darauf folgende Teil prüft, ob wir eine Eigenschaft mit passendem Namen zur Textbox finden können. Ebenso checken wir, ob der Typ zur Textbox passt, es sich dabei also um einen <a href="https://docs.microsoft.com/de-de/dotnet/api/system.string?view=net-6.0" target="_blank" rel="noreferrer noopener">String</a> handelt.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Dim nameWithoutPrefix = tb.Name.Substring(2)
Dim matchingProperty = properties.SingleOrDefault(Function(x) x.Name = nameWithoutPrefix)
If matchingProperty Is Nothing OrElse matchingProperty.PropertyType IsNot GetType(String) Then
    Continue For
End If</pre>



<p>Der letzte und wichtigste Part – also nach dem Motto &#8222;das Beste kommt zum Schluss&#8220; – ist, die Text-Eigenschaft der Textbox zu setzen:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">tb.Text = matchingProperty.GetValue(obj).ToString()</pre>



<p>Dazu verwenden wir die <strong><a href="https://docs.microsoft.com/de-de/dotnet/api/system.reflection.propertyinfo.getvalue?view=net-6.0" target="_blank" rel="noreferrer noopener">&#8222;GetValue&#8220;-Funktion</a></strong> der &#8222;PropertyInfo&#8220;-Klasse, um an den hinterlegten Wert der Eigenschaft zu kommen.</p>



<h2 class="wp-block-heading">Kompletter Code</h2>



<p>Wie immer fasse ich hier am Ende des Beitrages den kompletten Code zusammen.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="kompletter-code">Imports System.Runtime.CompilerServices

Module modExtensions

    &lt;Extension()>
    Public Sub Fill(frm As Form, obj As Object)
        Dim textBoxes = frm.Controls.OfType(Of TextBox)
        Dim properties = obj.GetType().GetProperties()

        For Each tb In textBoxes

            Dim wrongPrefix = Not tb.Name.StartsWith("tb")
            If wrongPrefix Then
                Continue For
            End If

            Dim nameWithoutPrefix = tb.Name.Substring(2)
            Dim matchingProperty = properties.SingleOrDefault(Function(x) x.Name = nameWithoutPrefix)
            If matchingProperty Is Nothing OrElse matchingProperty.PropertyType IsNot GetType(String) Then
                Continue For
            End If

            tb.Text = matchingProperty.GetValue(obj).ToString()
        Next
    End Sub

End Module
</pre>



<pre class="EnlighterJSRAW" data-enlighter-language="csharp" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="C#" data-enlighter-group="kompletter-code">using System;
using System.Windows.Forms;

namespace AutoFillFormCS
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnAutoFill_Click(object sender, EventArgs e)
        {
            var customer = new Customer()
            {
                Company = "Nice ltd.",
                FirstName = "Max",
                LastName = "Random",
                Street = "The street",
                HouseNo = "11a"
            };
            this.Fill(customer);
        }
    }
}
</pre>



<h2 class="wp-block-heading">Weiterführende Links</h2>



<ul class="wp-block-list"><li><strong><a href="https://robbelroot.de/blog/mvvm-csharp/" target="_blank" rel="noreferrer noopener">MVVM – Model View ViewModel</a></strong> (Wissen auch für VB geeignet)</li><li><a href="https://robbelroot.de/blog/mahapps-metro-projekt-aufsetzen/" target="_blank" rel="noreferrer noopener"><strong>Mahapps Metro Projekt aufsetzen</strong></a></li><li><strong><a href="https://robbelroot.de/blog/vbnet-await/" target="_blank" rel="noreferrer noopener">Asynchrone Programmierung</a></strong></li></ul>



<h2 class="wp-block-heading">Downloads</h2>



<div class="wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link" href="/downloads/vbnet/AutoFillForm.zip" target="_blank" rel="noreferrer noopener">AutoFillFormVB.zip</a></div>



<div class="wp-block-button"><a class="wp-block-button__link" href="/downloads/vbnet/AutoFillFormCS.zip" target="_blank" rel="noreferrer noopener">AutoFillFormCS.zip</a></div>
</div>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vbnet-formular-automatisch-ausfuellen-winforms/">VB NET Formular automatisch ausfüllen (Winforms)</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/vbnet-formular-automatisch-ausfuellen-winforms/feed/</wfw:commentRss>
			<slash:comments>3</slash:comments>
		
		
			</item>
		<item>
		<title>VBS Replace</title>
		<link>https://robbelroot.de/blog/vbs-replace/</link>
					<comments>https://robbelroot.de/blog/vbs-replace/#respond</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Fri, 16 Jul 2021 04:33:59 +0000</pubDate>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Visual Basic Script]]></category>
		<category><![CDATA[Visual Basic Script lernen]]></category>
		<category><![CDATA[basic]]></category>
		<category><![CDATA[ersetzen]]></category>
		<category><![CDATA[placeholder]]></category>
		<category><![CDATA[platzhalter]]></category>
		<category><![CDATA[replace]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[template]]></category>
		<category><![CDATA[templating]]></category>
		<category><![CDATA[vb]]></category>
		<category><![CDATA[vbs]]></category>
		<category><![CDATA[vbscript]]></category>
		<category><![CDATA[visual]]></category>
		<category><![CDATA[visual basic script]]></category>
		<category><![CDATA[vorlage]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=4259</guid>

					<description><![CDATA[<p>VBS Replace Du möchtest mit der VBS Replace Funktion Teile von Zeichenfolgen ersetzen und benötigst es z. B. für Platzhalter aus einem Email&#8211;Template? Starte jetzt mit diesem Post durch und lerne wie man unter anderem dazu die VBS Replace Funktion verwenden kann. Ggf. sind auch noch andere Beiträge von Interesse &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vbs-replace/">VBS Replace</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><a href="https://robbelroot.de/wp-content/uploads/2021/07/VBS-Replace.png"><img loading="lazy" decoding="async" width="1024" height="536" src="https://robbelroot.de/wp-content/uploads/2021/07/VBS-Replace-1024x536.png" alt="VBS Replace" class="wp-image-4262" title="VBS Replace" srcset="https://robbelroot.de/wp-content/uploads/2021/07/VBS-Replace-1024x536.png 1024w, https://robbelroot.de/wp-content/uploads/2021/07/VBS-Replace-300x157.png 300w, https://robbelroot.de/wp-content/uploads/2021/07/VBS-Replace-768x402.png 768w, https://robbelroot.de/wp-content/uploads/2021/07/VBS-Replace-700x366.png 700w, https://robbelroot.de/wp-content/uploads/2021/07/VBS-Replace-332x174.png 332w, https://robbelroot.de/wp-content/uploads/2021/07/VBS-Replace.png 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a><figcaption>VBS Replace</figcaption></figure>






<h2 class="wp-block-heading">VBS Replace</h2>



<p>Du möchtest mit der <strong>VBS Replace</strong> Funktion Teile von <strong>Zeichenfolgen ersetzen</strong> und <strong>benötigst </strong>es z. B. für Platzhalter aus einem <strong>Email</strong>&#8211;<strong>Template</strong>?</p>



<p><strong>Starte jetzt </strong>mit diesem Post durch und <strong>lerne wie </strong>man unter anderem dazu die <strong>VBS Replace</strong> Funktion <strong>verwenden</strong> kann.</p>



<p><strong>Ggf.</strong> sind auch noch <strong>andere Beiträge</strong> von Interesse für Dich: <strong><a href="/blog/vbscript-if-else" target="_blank" rel="noreferrer noopener">VBScript If-Else</a></strong>, <strong><a href="/blog/vbscript-instr" target="_blank" rel="noreferrer noopener">InStr</a></strong>, <strong><a href="/blog/vbs-msgbox" target="_blank" rel="noreferrer noopener">MsgBox</a></strong>.</p>



<h2 class="wp-block-heading">Unverzichtbar</h2>



<p><strong>Falls</strong> Du nicht schon durch einen <strong>konkreten Grund </strong>selbst auf die <strong>Funktion </strong>gestoßen bist, bist Du <strong>bestimmt</strong> durch <strong>andere Suchvoränge</strong> zum Replace-Befehl gekommen.</p>



<p><strong>Eventuell </strong>bist Du während deiner Recherche über Suchbegriffe,<strong> </strong>wie das <strong>Ersetzen </strong>von <strong><a href="https://de.wikipedia.org/wiki/Platzhalter" target="_blank" rel="noreferrer noopener">Platzhaltern</a></strong>, auf die VBS Replace Funktion gestoßen.</p>



<p>Mit <strong>großer Wahrscheinlichkeit </strong>hast Du auch schon <strong>Emails bekommen</strong>, wo <strong>Platzhalter nicht korrekt verarbeitet</strong> wurden.</p>



<p>Die <strong>Emails </strong>waren dann vermutlich <strong>mit kryptische Zeichen </strong>wie Diese hier versehen: &#8222;Hallo lieber {%firstName%}..&#8220;.</p>



<h3 class="wp-block-heading">Allgemeine Erklärung</h3>



<p><strong>So </strong>kann z. B. eine <strong>dieser Emails </strong>aussehen, Welche man <strong>bei </strong>der <strong>erfolgreichen Registrierung </strong>auf einer Seite durch das System geschickt bekommt:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;!DOCTYPE html>
&lt;html lang="de">
&lt;head>
  &lt;meta charset="UTF-8">
  &lt;meta http-equiv="X-UA-Compatible" content="IE=edge">
  &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
  &lt;title>{% SUBJECT %}&lt;/title>
&lt;/head>
&lt;body>
  &lt;div class="content">
    &lt;h1>Thanks for joining {% PRODUCT_NAME %}&lt;/h1>
    &lt;h2>Your right way of ...&lt;/h2>
    &lt;p>
      Thanks for joining {% SALUTATION %} {% LAST_NAME %},
      click here to start {% APP_LINK %}
    &lt;/p>
  &lt;/div>
&lt;/body>
&lt;/html></pre>



<p><strong>Dabei </strong>stellen die durch die &#8222;{%&#8220;, bzw. &#8222;%}&#8220; eingeschlossenen Wörter wie &#8222;SUBJECT&#8220; so etwas <strong>wie Variablen</strong> dar.</p>



<p>Final – also <strong>nach </strong>der <strong>Verarbeitung </strong>– <strong>könnte </strong>der Text, bzw. der HTML-Code dann wie <strong>folgt aussehen</strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;!DOCTYPE html>
&lt;html lang="de">
&lt;head>
  &lt;meta charset="UTF-8">
  &lt;meta http-equiv="X-UA-Compatible" content="IE=edge">
  &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
  &lt;title>Your registration&lt;/title>
&lt;/head>
&lt;body>
  &lt;div class="content">
    &lt;h1>Thanks for joining RobbelRoot.de&lt;/h1>
    &lt;h2>Your right way of ...&lt;/h2>
    &lt;p>
      Thanks for joining Mr. Skibbe,
      click here to start https://robbelroot.de
    &lt;/p>
  &lt;/div>
&lt;/body>
&lt;/html></pre>



<p><strong>Dort </strong>sehen wir <strong>dann die eigentlichen Daten</strong>, Welche sich <strong>hinter den Platzhaltern </strong>versteckt haben.</p>



<p><strong>Vielleicht </strong>wird <strong>nun </strong>ein wenig <strong>verständlicher</strong>, warum, bzw. wann solche Platzhalter übrig bleiben.</p>



<p><strong>Neben </strong>Email-<strong>Templates </strong>werden ähnliche Dinge auch <strong>in </strong>vielen Bekannten &#8222;<strong>Sprachen</strong>&#8220; <strong>wie </strong>z. B. <strong>VueJS </strong>verwendet.</p>



<p><strong>Dies </strong>macht man <strong>z. B.</strong>, <strong>damit </strong>der <strong>Parser </strong>der Sprache <strong>anschließend </strong>weiß, was er – vor allem nach eventueller Arbeit – <strong>wo hin </strong>setzen muss.</p>



<p><strong>Im Endeffekt </strong>sieht dies <strong>fast gleich </strong>zu oben aus, <strong>mit </strong>dem einen <strong>Unterschied</strong>, <strong>dass </strong>die verarbeitenden <strong>Werkzeuge </strong>damit <strong>anders umgehen</strong>.</p>



<p><strong>Hier </strong>kannst Du so ein kleines <strong>Vue Code-Schnipselchen</strong> sehen:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="html" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">          &lt;div class="col-3">
            &lt;div class="column">
              &lt;div class="text-subtitle2 text-center">
                {{ $t("statistics.yearlyGoalSubtitle") }}
              &lt;/div>
              &lt;div class="text-subtitle1 text-center">
                {{ yearlyProfit.toFixed(2) + " / " + yearlyGoal }}
              &lt;/div>
            &lt;/div>
          &lt;/div></pre>



<p><strong>In </strong>dem <strong>Vue-Beispiel</strong> <strong>passiert </strong>allerdings wie schon erwähnt ein wenig <strong>mehr</strong>, <strong>als </strong>die <strong>bloße Ersetzung </strong>von &#8222;A&#8220; durch &#8222;B&#8220;.</p>



<p><strong>Neben </strong>dem <strong>Funktions-Aufruf</strong> findet hier auch <strong>noch </strong>die <strong>Verkettung </strong>eines Strings, also einer <strong>Zeichenkette </strong>statt.</p>



<p>Ich <strong>denke </strong>allerdings, dass dies <strong>zum </strong>aktuellen <strong>Zeitpunkt </strong>für die Erklärung <strong>ausreicht </strong>und den ein oder anderen sonst verwirren könnte.</p>



<h2 class="wp-block-heading">VBS Replace Funktion </h2>



<p><strong>Ehe</strong> wir mit fiktiven Beispielen <strong>starten</strong>, <strong>schauen </strong>wir uns die <strong>Details </strong>der Funktion selbst <strong>an</strong>:</p>



<h3 class="wp-block-heading">Parameter</h3>



<h4 class="wp-block-heading">string</h4>



<p>Dieser Parameter gibt den String an, <strong>worin gesucht </strong>werden soll.</p>



<h4 class="wp-block-heading">find </h4>



<p>Hiermit geben wir den <strong>String </strong>an, <strong>nach Welchem</strong> wir letztendlich <strong>suchen</strong>.</p>



<h4 class="wp-block-heading">replacewith</h4>



<p>Dieser String bestimmt, <strong>wodurch </strong>der gefundene String <strong>ersetzt </strong>werden soll.</p>



<h4 class="wp-block-heading">start [optional]</h4>



<p>Definiert die Position ab wo das Ersetzen beginnt.</p>



<p><strong>Achtung:</strong> Entfernt alle vorherigen Zeichenfolgen.</p>



<h4 class="wp-block-heading">count [optional]</h4>



<p><strong>Standardmäßig </strong>auf <strong>-1</strong> werden <strong>alle Vorkommnisse</strong> ersetzt, allerdings kann man durch diesen Parameter auch eine Art <strong>Begrenzungsmöglichkeit</strong> setzen.</p>



<h4 class="wp-block-heading">compare [optional]</h4>



<p>Konfiguriert die <strong>Vergleichs</strong>-Methode, wo wir 2 Möglichkeiten haben: <strong>vbBinaryCompare</strong>, <strong>vbTextCompare</strong>.</p>



<p>Die <strong>erste</strong> <strong>Option </strong>verwendet den <strong>binären Vergleich</strong>, wobei die <strong>Strings im Vergleich</strong> eine <strong>exakte Übereinstimmung </strong>haben müssen.</p>



<p>Die <strong>zweite Option </strong>gibt an, dass der <strong>Vergleich</strong> eine <strong>groß</strong>&#8211; und <strong>kleinschreibungs</strong>-unabhängige Methode an.</p>



<h2 class="wp-block-heading">Code – VBS Replace</h2>



<p>In diesem Abschnitt kannst Du nun <strong>ein oder mehrere Beispiele </strong>zur Funktion sehen:</p>



<h3 class="wp-block-heading">Einfaches Beispiel</h3>



<p>Im ersten Beispiel <strong>deklariere</strong> ich die &#8222;<strong>msg</strong>&#8222;-<strong>Variable</strong>, mit anschließendem <strong>Wert </strong>&#8222;This is a beautiful day!&#8220;.</p>



<p>Im nächsten Schritt <strong>ersetze</strong> ich das &#8222;<strong>beautiful</strong>&#8220; <strong>durch </strong>&#8222;<strong>perfect</strong>&#8220; und es kommt <strong>diese Nachricht</strong> zu Stande:</p>



<figure class="wp-block-image size-large"><a href="https://robbelroot.de/wp-content/uploads/2021/07/VBScript-Replace-Beispiel.png"><img loading="lazy" decoding="async" width="151" height="136" src="https://robbelroot.de/wp-content/uploads/2021/07/VBScript-Replace-Beispiel.png" alt="VBS Replace" class="wp-image-4256" title="VBS Replace"/></a><figcaption>VBS Replace Beispiel</figcaption></figure>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Dim msg
msg = "This is a beautiful day!"
msg = Replace(msg, "beautiful", "perfect")
MsgBox(msg)</pre>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vbs-replace/">VBS Replace</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/vbs-replace/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>VBS InStr</title>
		<link>https://robbelroot.de/blog/vbs-instr/</link>
					<comments>https://robbelroot.de/blog/vbs-instr/#respond</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Thu, 15 Jul 2021 15:14:26 +0000</pubDate>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Visual Basic Script]]></category>
		<category><![CDATA[Visual Basic Script lernen]]></category>
		<category><![CDATA[basic]]></category>
		<category><![CDATA[between]]></category>
		<category><![CDATA[contains]]></category>
		<category><![CDATA[in]]></category>
		<category><![CDATA[inside]]></category>
		<category><![CDATA[instr]]></category>
		<category><![CDATA[script]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[str]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[vbs]]></category>
		<category><![CDATA[vbscript]]></category>
		<category><![CDATA[visual]]></category>
		<category><![CDATA[visual basic]]></category>
		<category><![CDATA[visual basic script]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=4188</guid>

					<description><![CDATA[<p>VBS InStr Du willst mit der VBS InStr Funktion überprüfen, ob ein String sich innerhalb eines Anderen befindet? Dann freut es mich, Dir in diesem Beitrag die passende InStr-Funktion vorzustellen! Eventuell hast Du zu einem späteren Zeitpunkt auch Interesse an einem der folgenden Beiträge: VBScript Array, MsgBox. Hintergrund – VBS &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vbs-instr/">VBS InStr</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><a href="https://robbelroot.de/wp-content/uploads/2021/07/VBScript-InStr.png"><img loading="lazy" decoding="async" width="1024" height="536" src="https://robbelroot.de/wp-content/uploads/2021/07/VBScript-InStr-1024x536.png" alt="VBS InStr" class="wp-image-4156" title="VBS InStr" srcset="https://robbelroot.de/wp-content/uploads/2021/07/VBScript-InStr-1024x536.png 1024w, https://robbelroot.de/wp-content/uploads/2021/07/VBScript-InStr-300x157.png 300w, https://robbelroot.de/wp-content/uploads/2021/07/VBScript-InStr-768x402.png 768w, https://robbelroot.de/wp-content/uploads/2021/07/VBScript-InStr-700x366.png 700w, https://robbelroot.de/wp-content/uploads/2021/07/VBScript-InStr-332x174.png 332w, https://robbelroot.de/wp-content/uploads/2021/07/VBScript-InStr.png 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a><figcaption>VBS InStr</figcaption></figure>






<h2 class="wp-block-heading">VBS InStr</h2>



<p>Du <strong>willst</strong> mit der <strong>VBS InStr</strong> Funktion <strong>überprüfen</strong>, <strong>ob </strong>ein <strong>String sich innerhalb </strong>eines <strong>Anderen </strong>befindet?</p>



<p>Dann <strong>freut</strong> es <strong>mich,</strong> Dir in diesem Beitrag die passende <strong>InStr-Funktion</strong> <strong>vorzustellen</strong>!</p>



<p><strong>Eventuell</strong> hast Du zu einem späteren Zeitpunkt auch <strong>Interesse an </strong>einem der folgenden <strong>Beiträge</strong>: <strong><a href="/blog/vbscript-array" target="_blank" rel="noreferrer noopener">VBScript Array</a></strong>, <strong><a href="/blog/vbscript-msgbox" target="_blank" rel="noreferrer noopener">MsgBox</a></strong>.</p>



<h2 class="wp-block-heading">Hintergrund – VBS InStr</h2>



<p>Zu gut kennt man es als Softwareentwickler, <strong>überprüfen </strong>zu <strong>müssen</strong>, <strong>ob </strong>ein <strong>String </strong>ein Teil eines <strong>anderen Strings </strong>ist.</p>



<p>Je nach Aufgabenstellung ist es <strong>auch von Bedeutung</strong>, an <strong>welcher exakten Position </strong>dieser andere <strong>String ist</strong>, bzw. ab wo Er startet.</p>



<p>Eine <strong>vergleichbare </strong>Funktion finden wir im <strong>.NET</strong>-Umfeld, die <strong><a href="https://docs.microsoft.com/de-de/dotnet/api/system.string.contains?view=net-5.0" target="_blank" rel="noreferrer noopener">Contains-Funktion</a></strong>, Welche uns leider <strong>in VBScript nicht zur Verfügung </strong>steht.</p>



<p><strong>Mach </strong>dir jedoch <strong>keine Sorgen</strong>, denn <strong>auch </strong>in <strong>VBScript</strong> <strong>haben </strong>wir die <strong>Möglichkeit </strong>eine <strong>ähnliche Methode</strong> zu <strong>verwenden</strong>.</p>



<h2 class="wp-block-heading">Die Nadel im Heuhaufen – String durchsuchen</h2>



<p>Die Möglichkeit die uns VBS (Visual Basic Script) hier bietet, ist die <strong>InStr Funktion</strong>.</p>



<p>&#8222;InStr&#8220; <strong>ermittelt</strong> für uns in einem <strong>angegebenen String</strong> die <strong>Position </strong>eines Such-Strings.</p>



<p><strong>Wenn </strong>der Such-String <strong>nicht </strong>innerhalb des Ziel-Strings <strong>gefunden </strong>wird, <strong>wird </strong>von der Funktion eine <strong>0 zurückgegeben</strong>.</p>



<p>Wir haben <strong>sogar </strong>die <strong>Möglichkeit </strong>den <strong>Modus für </strong>den <strong>Vergleich </strong>zu <strong>bestimmen</strong>, wozu wir sofort kommen werden.</p>



<h2 class="wp-block-heading">Die InStr-Funktion aus VBS</h2>



<p><strong>Schauen wir </strong>uns nun <strong>die</strong> Signatur der <strong>InStr</strong>-Funktion an:</p>



<h3 class="wp-block-heading">Parameter</h3>



<h4 class="wp-block-heading">[Optional] start [Integer]</h4>



<p>Der erste Parameter der Funktion <strong>gibt </strong>die <strong>Start-Position der Suche an</strong>.</p>



<p><strong>Wenn </strong>die Start-Position <strong>ausgelassen</strong> wird, <strong>beginnt </strong>die Suche automatisch am<strong> Anfang</strong>.</p>



<h4 class="wp-block-heading">string1 [String]</h4>



<p><strong>Hierbei </strong>handelt es sich um den zu <strong>durchsuchenden String</strong>.</p>



<h4 class="wp-block-heading">string2 [String]</h4>



<p>Dieser String gibt an, <strong>wonach </strong>im ersten String <strong>gesucht werden soll</strong>.</p>



<h4 class="wp-block-heading">[Optional] compare [Integer]</h4>



<p><strong>Hiermit </strong>legen wir die <strong>Art </strong>des <strong>Vergleichs aus </strong>folgender <strong>Tabelle </strong>fest:</p>



<figure class="wp-block-table is-style-stripes"><table><thead><tr><th class="has-text-align-left" data-align="left"><strong>Name</strong></th><th class="has-text-align-left" data-align="left"><strong>Wert</strong></th><th class="has-text-align-left" data-align="left"><strong>Beschreibung</strong></th></tr></thead><tbody><tr><td class="has-text-align-left" data-align="left"><strong>vbUseCompareOption</strong></td><td class="has-text-align-left" data-align="left">-1</td><td class="has-text-align-left" data-align="left">Führt Vergleich mit Option Compare-Anweisung aus.</td></tr><tr><td class="has-text-align-left" data-align="left"><strong>vbBinaryCompare</strong></td><td class="has-text-align-left" data-align="left">0</td><td class="has-text-align-left" data-align="left">Verwendet einen binären Vergleich</td></tr><tr><td class="has-text-align-left" data-align="left"><strong>vbTextCompare</strong></td><td class="has-text-align-left" data-align="left">1</td><td class="has-text-align-left" data-align="left">Nutzt einen Textvergleich</td></tr><tr><td class="has-text-align-left" data-align="left"><strong>vbDatabaseCompare</strong></td><td class="has-text-align-left" data-align="left">2</td><td class="has-text-align-left" data-align="left">Verwendet bei Microsoft Access einen Datenbankvergleich</td></tr></tbody></table><figcaption>VBS InStr Compare Optionen</figcaption></figure>



<p><strong>Falls</strong> man diese Option <strong>auslässt</strong>, wird ein <strong>binärer Vergleich </strong>genutzt.</p>



<p>Die beiden für uns <strong>bedeutsamen Arten sind </strong>Diese: <strong>vbBinaryCompare</strong> und <strong><strong>vbTextCompare</strong></strong>.</p>



<p>Mit der Option &#8222;<strong>vbBinaryCompare</strong>&#8220; wird <strong>binär </strong>verglichen, dass heißt, dass die <strong>Zeichenfolgen eine exakte Übereinstimmung </strong>haben müssen.</p>



<p>Die <strong>vbTextCompare</strong>-Option gibt bereits bei einer <strong>textlichen Übereinstimmung – ohne Groß</strong>&#8211; und <strong>Kleinschreibung</strong> – positives Feedback.</p>



<h2 class="wp-block-heading">Code – VBS InStr</h2>



<p><strong>Hier </strong>möchte ich Dir ein <strong>paar Beispielcodes </strong>zeigen:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Dim str
str = "Hello my world"
Dim search
search = "my"
Dim res
res = InStr(1, str, search)
MsgBox(res)</pre>



<p>In diesem Beispiel wird der <strong>String </strong>als &#8222;str&#8220; <strong>deklariert und </strong>danach mit dem Wert &#8222;Hello my world&#8220; <strong>befüllt</strong>.</p>



<p>Anschließend <strong>deklarieren </strong>wir einen <strong>zusätzlichen String </strong>namens &#8222;search&#8220;, wonach wir suchen werden, Ihm weisen wir den <strong>Wert </strong>&#8222;my&#8220; <strong>zu</strong>.</p>



<p>Im <strong>vorletzten Schritt </strong>deklarieren wir die <strong>Variable </strong>namens &#8222;res&#8220;, Welche den <strong>Rückgabewert </strong>unseres &#8222;InStr&#8220;-<strong>Aufrufs </strong>zwischenspeichern wird.</p>



<p>In diesem Beispiel bekommen wir den <strong>Rückgabewert 7</strong>, <strong>da </strong>das <strong>Wort </strong>&#8222;my&#8220; <strong>ab </strong>der <strong>7. Position startet</strong>.</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vbs-instr/">VBS InStr</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/vbs-instr/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>VB String Array</title>
		<link>https://robbelroot.de/blog/vb-string-array/</link>
					<comments>https://robbelroot.de/blog/vb-string-array/#respond</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Tue, 13 Jul 2021 10:03:48 +0000</pubDate>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Visual Basic]]></category>
		<category><![CDATA[Visual Basic lernen]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[auflisten]]></category>
		<category><![CDATA[basic]]></category>
		<category><![CDATA[datenfeld]]></category>
		<category><![CDATA[datenfelder]]></category>
		<category><![CDATA[feld]]></category>
		<category><![CDATA[felder]]></category>
		<category><![CDATA[list]]></category>
		<category><![CDATA[listing]]></category>
		<category><![CDATA[mehrfach]]></category>
		<category><![CDATA[multiple]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[vb]]></category>
		<category><![CDATA[visual]]></category>
		<category><![CDATA[visual basic]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=3847</guid>

					<description><![CDATA[<p>VB String Array Du bist bei deiner &#8222;VB String Array&#8222;-Recherche auf meine Seite gestoßen und möchtest wissen, wie man ein String&#8211;Array in Visual Basic erstellen kann? Eventuell weißt Du auch bereits, wie man ein String&#8211;Array erstellt, Dir fehlt aber vielleicht der Feinschliff, oder Du hättest gerne mehr Tipps? Vielleicht interessierst &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vb-string-array/">VB String Array</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><a href="https://robbelroot.de/wp-content/uploads/2021/07/VB-String-Array.png"><img loading="lazy" decoding="async" width="1024" height="536" src="https://robbelroot.de/wp-content/uploads/2021/07/VB-String-Array-1024x536.png" alt="VB String Array" class="wp-image-3852" title="VB String Array" srcset="https://robbelroot.de/wp-content/uploads/2021/07/VB-String-Array-1024x536.png 1024w, https://robbelroot.de/wp-content/uploads/2021/07/VB-String-Array-300x157.png 300w, https://robbelroot.de/wp-content/uploads/2021/07/VB-String-Array-768x402.png 768w, https://robbelroot.de/wp-content/uploads/2021/07/VB-String-Array-700x366.png 700w, https://robbelroot.de/wp-content/uploads/2021/07/VB-String-Array-332x174.png 332w, https://robbelroot.de/wp-content/uploads/2021/07/VB-String-Array.png 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a><figcaption>VB String Array</figcaption></figure>






<h2 class="wp-block-heading">VB String Array</h2>



<p>Du bist bei deiner &#8222;<strong>VB String Array</strong>&#8222;-Recherche auf <strong>meine Seite</strong> gestoßen und möchtest <strong>wissen</strong>, <strong>wie </strong>man ein <strong>String</strong>&#8211;<strong>Array </strong>in <strong>Visual Basic</strong> erstellen kann?</p>



<p><strong>Eventuell weißt </strong>Du auch <strong>bereits</strong>, wie man ein <strong>String</strong>&#8211;<strong>Array erstellt</strong>, Dir <strong>fehlt </strong>aber <strong>vielleicht </strong>der <strong>Feinschliff</strong>, oder Du hättest gerne <strong>mehr Tipps</strong>?</p>



<p>Vielleicht <strong>interessierst </strong>Du Dich noch für die <strong>folgenden Beiträge</strong>: <strong><a href="/blog/vb-array" target="_blank" rel="noreferrer noopener">Arrays allgemein</a></strong>.</p>



<h2 class="wp-block-heading">Wiederholung Arrays</h2>



<p><strong>Wie </strong>Du <strong>ggf</strong>. schon <strong>in </strong>meinem <strong>anderen Beitrag</strong>, <strong>oder durch </strong>Dein <strong>Vorwissen </strong>weißt, <strong>speichern Arrays mehrere Daten </strong>auf einmal.</p>



<p><strong>Vergleichbar </strong>ist das <strong>Array mit </strong>einer Art <strong>Liste</strong>, Welche <strong>gezählt</strong>, wie eine Variable <strong>veränderbar </strong>und <strong>auch iterierbar </strong>ist.</p>



<p>Schon in meinem anderen Beitrag habe ich auch <strong>darauf hingewiesen</strong>, dass es einige <strong>Kniffe wie </strong>z. B. <strong>in </strong>der <strong>Deklarationsweise gibt</strong>.</p>



<h2 class="wp-block-heading">Mögliche Szenarien</h2>



<p>Wenn man an ein <strong>String-Array</strong> denkt, bzw. die <strong>Notwendigkeit </strong>dazu hat, verbindet man das eventuell mit <strong>folgenden Szenarien</strong>: </p>



<ul class="wp-block-list"><li>Man könnte z. B. <strong>Rechnungsnummern </strong>(Welche durchaus auch Buchstaben enthalten können) <strong>durchlaufen </strong>wollen</li><li>Es ist die Notwendigkeit einer <strong>Auflistung von Namen </strong>vorhanden</li><li>Ein <strong>String soll </strong>zum Beispiel <strong>in </strong>seine <strong>Bestandteile zerlegt </strong>und in einem <strong>Array gespeichert </strong>werden</li><li>uvm.</li></ul>



<h2 class="wp-block-heading">Auflistung von Namen – VB String Array</h2>



<p>Schauen wir uns für das Beispiel mal ein <strong>konkretes Szenario </strong>an, dazu <strong>speichern </strong>wir verschiedene <strong>Vornamen in </strong>ein <strong>String-Array</strong>.</p>



<p><strong>Zuerst sehen </strong>wir uns dazu die <strong>Deklaration</strong>, bzw. die <strong>Initialisierung </strong>eines <strong>String-Arrays</strong> in <strong>Visual Basic</strong> an.</p>



<p><strong>Anschließend </strong>gehen wir <strong>weitere Operationen </strong>am Array <strong>wie </strong>das <strong>Hinzufügen </strong>weiterer <strong>Vornamen </strong>an.</p>



<h2 class="wp-block-heading">Deklaration eines String-Arrays</h2>



<p><strong>Wie </strong>gleich <strong>folgend, </strong>könnte die <strong>Deklaration </strong>eines String-Arrays <strong>aussehen</strong>.</p>



<p>Das <strong>bedeutet</strong>, dass das <strong>Array nicht </strong>bereits von <strong>vornherein </strong>seine <strong>Speicherkapazität festgelegt </strong>bekommt.</p>



<p><strong>Übersetzen </strong>könnte <strong>man </strong>die <strong>Zeile </strong>als: &#8222;<strong>Lege </strong>die <strong>Variable </strong>firstNames als <strong>String-Array</strong> fest.&#8220;</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Dim firstNames As String()</pre>



<h2 class="wp-block-heading">Initialisierung eines String-Arrays</h2>



<p>Nun <strong>folgt </strong>die <strong>Initialisierung </strong>eines <strong>String-Arrays</strong>.</p>



<p>Das <strong>bedeutet</strong>, wir <strong>deklarieren </strong>ebenfalls die <strong>Variable </strong>&#8222;firstNames&#8220; <strong>und</strong> <strong>weisen </strong>Ihr initial <strong>Werte</strong> <strong>zu</strong>.</p>



<p>Der <strong>höchste Index</strong> des <strong>Arrays </strong>ist nun somit der <strong>Eintrag </strong>namens &#8222;<strong>Cathrine</strong>&#8220; mit dem <strong>Wert 2</strong>. </p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Dim firstNames As String() = {"John", "Max", "Cathrine"}</pre>



<h2 class="wp-block-heading">Hinzufügen eines Elements in VB String Array</h2>



<p><strong>Nachdem </strong>das <strong>Array </strong>vorher entweder mit dem einem, oder dem Anderen Weg <strong>definiert wurde</strong>, <strong>kommt </strong>man <strong>vermutlich </strong>auch an den Punkt, <strong>weitere Elemente hinzufügen </strong>zu wollen.</p>



<p>Dafür müssen wir <strong>dem Array</strong>, was andernfalls einen Index-Fehler werfen würde <strong>sagen</strong>, dass dessen <strong>Kapazität </strong>mit Hilfe der <strong><a href="https://docs.microsoft.com/de-de/office/vba/language/reference/user-interface-help/redim-statement" target="_blank" rel="noreferrer noopener">ReDim-Anweisung</a></strong> <strong>neu definiert </strong>wird.</p>



<p><strong>Zusätzlich </strong>verwenden wir das &#8222;<strong>Preserve</strong>&#8222;-<strong>Schlüsselwort</strong>, um die <strong>vorherigen Einträge </strong>zu <strong>behalten</strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ReDim Preserve firstNames(3)</pre>



<p><strong>Beachte </strong>hierbei, <strong>dass </strong>die <strong>Zahl </strong>in der Klammer – also die <strong>Dimension </strong>/ Kapazität – auch hier in der Form eines <strong>Indexes </strong>(also beginnend bei 0) <strong>angegeben </strong>werden <strong>muss</strong>.</p>



<p><strong>Danach </strong>können wir einen, oder mehrere weitere <strong>Namen </strong>in das <strong>String-Array hinzufügen</strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">firstNames(3) = "Michael"</pre>



<h2 class="wp-block-heading">Entfernen des letzten Elements</h2>



<p><strong>Um </strong>bei diesem String-Array z. B. den <strong>letzten Eintrag wieder entfernen </strong>zu können, können wir ebenfalls die &#8222;<strong>ReDim </strong>&amp; <strong>Preserve&#8220;</strong>-Kombination verwenden.</p>



<p>Hier zeige ich <strong>kurz </strong>eine <strong>Variante</strong>, wo ich die <strong>Zahl </strong>praktisch <strong>fest</strong> in den Code schreibe, <strong>nicht </strong>so <strong>prickelnd</strong>, <strong>aber funktionierend</strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ReDim Preserve firstNames(2)</pre>



<p><strong>Etwas besser </strong>wäre es <strong>natürlich</strong>, wenn das Ganze <strong>dynamisch </strong>funktionieren würde, dazu können wir die <strong>Obergrenze </strong>einfach <strong>ausmachen und 1</strong> davon <strong>abziehen</strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">ReDim Preserve firstNames(UBound(firstNames) - 1)</pre>



<p><strong>Beachte </strong>hier, dass Du ggf. <strong>mit </strong>einer <strong>If-Abfrage</strong> <strong>abfangen </strong>musst, dass <strong>nicht </strong>nachher <strong>-1</strong> bei der Berechnung <strong>rumkommt</strong>.</p>



<h2 class="wp-block-heading">Entfernen des ersten Elements</h2>



<p>Hier <strong>noch </strong>ein kleines Beispiel, <strong>wie </strong>man statt dem letzten, das <strong>erste Element </strong>des String-Arrays <strong>entfernen </strong>kann.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">For i = 1 To UBound(firstNames)
  firstNames(i - 1) = firstNames(i)
Next i
ReDim Preserve firstNames(UBound(firstNames) - 1)</pre>



<p><strong>Zuerst iterieren </strong>wir dafür <strong>beginnend </strong>bei <strong>1</strong> zum &#8222;<strong>Upper-Bound</strong>&#8222;, also der oberen &#8222;Index-Grenze&#8220; des <strong>Arrays</strong>.</p>



<p>In <strong>jedem Durchlauf </strong>der For-Schleife <strong>setzen </strong>wir an die jeweilige <strong>Index-Position &#8222;i-1&#8220;</strong>, den <strong>Wert </strong>der hinter <strong>des aktuellen i-Indexes</strong> steckt.</p>



<p>Anschließend <strong>korrigieren </strong>wir die <strong>Kapazität des Arrays</strong> durch die bekannte <strong>ReDim-Preserve</strong> Variante mit der <strong>UBound</strong>&#8211;<strong>Funktion</strong>.</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vb-string-array/">VB String Array</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/vb-string-array/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>VB.NET Anführungszeichen in String</title>
		<link>https://robbelroot.de/blog/vbnet-anfuehrungszeichen-in-string/</link>
					<comments>https://robbelroot.de/blog/vbnet-anfuehrungszeichen-in-string/#comments</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Mon, 12 Jul 2021 10:31:51 +0000</pubDate>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Visual Basic .NET]]></category>
		<category><![CDATA[Visual Basic .NET lernen]]></category>
		<category><![CDATA[anführungszeichen]]></category>
		<category><![CDATA[buchstabe]]></category>
		<category><![CDATA[character]]></category>
		<category><![CDATA[charakter]]></category>
		<category><![CDATA[escape]]></category>
		<category><![CDATA[im]]></category>
		<category><![CDATA[in]]></category>
		<category><![CDATA[inside]]></category>
		<category><![CDATA[mark]]></category>
		<category><![CDATA[net]]></category>
		<category><![CDATA[quotation]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[system]]></category>
		<category><![CDATA[vb.net]]></category>
		<category><![CDATA[vbnet]]></category>
		<category><![CDATA[zeichen]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=3703</guid>

					<description><![CDATA[<p>VB.NET Anführungszeichen in String Du möchtest in VB.NET Anführungszeichen in einem String darstellen, bzw. haben? Das ist kein Problem, lerne in diesem einfachen kleinen Beitrag, wie Du Anführungszeichen innerhalb eines Visual Basic .NET Strings darstellen kannst. Vielleicht interessierst Du Dich auch noch für folgende Beiträge: Erstes Zeichen aus String entfernen, &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vbnet-anfuehrungszeichen-in-string/">VB.NET Anführungszeichen in String</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<figure class="wp-block-image size-large"><a href="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String.png"><img loading="lazy" decoding="async" width="1024" height="536" src="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-1024x536.png" alt="VB.NET Anführungszeichen in String" class="wp-image-3706" title="VB.NET Anführungszeichen in String" srcset="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-1024x536.png 1024w, https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-300x157.png 300w, https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-768x402.png 768w, https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-700x366.png 700w, https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-332x174.png 332w, https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String.png 1200w" sizes="auto, (max-width: 1024px) 100vw, 1024px" /></a><figcaption>VB.NET Anführungszeichen in String</figcaption></figure>






<h2 class="wp-block-heading">VB.NET Anführungszeichen in String</h2>



<p>Du <strong>möchtest </strong>in <strong>VB.NET Anführungszeichen in einem String</strong> darstellen, bzw. haben?</p>



<p>Das ist <strong>kein Problem</strong>, <strong>lerne </strong>in diesem einfachen kleinen Beitrag, <strong>wie Du Anführungszeichen innerhalb </strong>eines Visual Basic .NET <strong><a href="https://docs.microsoft.com/de-de/dotnet/api/system.string?view=net-5.0" target="_blank" rel="noreferrer noopener">Strings</a> darstellen kannst</strong>.</p>



<p>Vielleicht <strong>interessierst </strong>Du Dich auch noch für <strong>folgende Beiträge</strong>: <strong><a href="/blog/vbnet-erstes-zeichen-aus-string-entfernen" target="_blank" rel="noreferrer noopener">Erstes Zeichen aus String entfernen</a></strong>, <strong><a href="/blog/vbnet-letztes-zeichen-aus-string-entfernen" target="_blank" rel="noreferrer noopener">letztes Zeichen aus String entfernen</a></strong> oder <strong><a href="/blog/vbnet-string-zerlegen" target="_blank" rel="noreferrer noopener">String zerlegen</a></strong>.</p>



<h2 class="wp-block-heading">Beispiel-Dialog</h2>



<p><strong>Vielleicht </strong>kommt Dir ein <strong>ähnlicher Dialog </strong>(MessageBox) <strong>wie Dieser </strong>hier <strong>bekannt </strong>vor:</p>



<figure class="wp-block-image size-large"><a href="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-Beispiel-Dialog.png"><img loading="lazy" decoding="async" width="359" height="158" src="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-Beispiel-Dialog.png" alt="VB.NET Anführungszeichen in String Beispiel-Dialog" class="wp-image-3713" title="VB.NET Anführungszeichen in String Beispiel-Dialog" srcset="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-Beispiel-Dialog.png 359w, https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-Beispiel-Dialog-300x132.png 300w, https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-Beispiel-Dialog-332x146.png 332w" sizes="auto, (max-width: 359px) 100vw, 359px" /></a><figcaption>VB.NET Anführungszeichen in String Beispiel-Dialog</figcaption></figure>



<p>Hier <strong>wurde </strong>z. B. <strong>nach </strong>einem <strong>Template </strong>namens &#8222;<strong>Default</strong>&#8220; <strong>gesucht</strong>, Welches dann aber nicht gefunden wurde.</p>



<p><strong>Wenn </strong>man <strong>statt </strong>des <strong>obigen Textes </strong>beispielsweise <strong>so etwas demonstriert </strong>bekommen würde, <strong>würde </strong>man <strong>sich </strong>sicher <strong>wundern</strong>:</p>



<figure class="wp-block-image size-large"><a href="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Beispiel-Dialog-ohne-Anfuehrungszeichen.png"><img loading="lazy" decoding="async" width="351" height="157" src="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Beispiel-Dialog-ohne-Anfuehrungszeichen.png" alt="VB.NET Beispiel-Dialog ohne Anführungszeichen" class="wp-image-3715" title="VB.NET Beispiel-Dialog ohne Anführungszeichen" srcset="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Beispiel-Dialog-ohne-Anfuehrungszeichen.png 351w, https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Beispiel-Dialog-ohne-Anfuehrungszeichen-300x134.png 300w, https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Beispiel-Dialog-ohne-Anfuehrungszeichen-332x149.png 332w" sizes="auto, (max-width: 351px) 100vw, 351px" /></a><figcaption>VB.NET Beispiel-Dialog ohne Anführungszeichen</figcaption></figure>



<p> </p>



<p>Das <strong>dürfte </strong>dann <strong>daran liegen</strong>, <strong>dass </strong>man <strong>meint</strong>, das &#8222;Default&#8220; <strong>Wort würde zum Satz </strong>selbst <strong>gehören </strong>und es sieht – nicht vorgehoben – <strong>irgendwie komisch </strong>aus.</p>



<h2 class="wp-block-heading">Erster Versuch – VB.NET Anführungszeichen in String</h2>



<p><strong>Sobald </strong>Du also <strong>in </strong>eine <strong>ähnliche Situation gerätst </strong>– und ich denke <strong>an diesem Punkt </strong>bist Du <strong>gerade,</strong> da Du meinen Beitrag gefunden hast – <strong>könntest </strong>Du es wie folgt <strong>probiert haben</strong>:</p>



<figure class="wp-block-image size-large"><a href="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-Fehler.png"><img loading="lazy" decoding="async" width="583" height="31" src="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-Fehler.png" alt="VB.NET Anführungszeichen in String Fehler" class="wp-image-3717" title="VB.NET Anführungszeichen in String Fehler" srcset="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-Fehler.png 583w, https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-Fehler-300x16.png 300w, https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Anfuehrungszeichen-in-String-Fehler-332x18.png 332w" sizes="auto, (max-width: 583px) 100vw, 583px" /></a><figcaption>VB.NET Anführungszeichen in String Fehler</figcaption></figure>



<p><strong>Allerdings </strong>würdest Du auf <strong>diese Weise </strong>einen <strong><a href="https://docs.microsoft.com/de-de/dotnet/visual-basic/language-reference/error-messages/end-of-statement-expected" target="_blank" rel="noreferrer noopener">&#8222;end of-Anweisung erwartet&#8220;-Fehler</a></strong> bekommen.</p>



<p><strong>Lass Dich </strong>hier <strong>durch </strong>das verwendete <strong>Dollar-Zeichen</strong> am Anfang des Strings <strong>und </strong>den <strong>geschweiften Klammern</strong> <strong>nicht verunsichern</strong>.</p>



<p>Diese &#8222;Technik&#8220; nennt sich <strong>Zeichenfolgeninterpolation </strong>und ist <strong>seit Visual Basic .NET 14</strong> <strong>verfügbar</strong>.</p>



<p>Seitdem <strong>nutze ich </strong>Diese <strong>ausgiebig </strong>und sehr gerne, <strong>da </strong>die Interpolation viel <strong>vereinfacht und verkürzt</strong>.</p>



<h2 class="wp-block-heading">Code-Frickeleien aus dem Netz</h2>



<p><strong>Wie so </strong>oft beim Coding, <strong>findet man </strong>im Netz viele <strong>Code</strong>&#8211;<strong>Frickeleien </strong>wie z. B. Diese hier:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Dim exampleMessage = $"Could not find template {Chr(34)}{templateName}{Chr(34)} inside the folder"</pre>



<h3 class="wp-block-heading">You shall not parse, bzw. leider doch..</h3>



<p>Man versucht hier <strong>durch </strong>die <strong><a href="https://docs.microsoft.com/de-de/dotnet/api/microsoft.visualbasic.strings.chr?view=net-5.0" target="_blank" rel="noreferrer noopener">&#8222;Chr&#8220;-Funktion</a></strong>, das dem <strong>Char-Code</strong> jeweilig <strong>zugrunde liegende Zeichen </strong>zu bekommen, was bei der <strong>Zahl 34 das Anführungszeichen</strong> wäre.</p>



<p><strong>Genau da </strong>finde ich <strong>fängt </strong>die <strong>Misere </strong>schon <strong>an</strong>, <strong>denn wer weiß nach </strong>einem vergangenen <strong>halben Jahr </strong>bitte <strong>noch</strong>, <strong>was </strong>die Zahl <strong>34 </strong>repräsentieren <strong>sollte</strong>.</p>



<p><strong>Auch wenn </strong>man jetzt die Zahl 34 <strong>durch </strong>eine passende <strong>Konstante ersetzen </strong>würde, <strong>wäre </strong>es <strong>suboptimal</strong>.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Public Const QUOTATION_MARK_CHAR_CODE = 34</pre>



<h3 class="wp-block-heading">Die bessere Variante</h3>



<p><strong>Ich </strong>persönlich <strong>bevorzuge </strong>normalerweise <strong>sprachunabhängige Hilfsmittel</strong>, <strong>daher </strong>würde ich definitiv <strong>auf </strong>die <strong>&#8222;Chr&#8220;-Funktion verzichten</strong> und einen anderen Weg suchen.</p>



<p>Die <strong>&#8222;Chr&#8220;-Funktion</strong> befindet sich im <strong><a href="https://docs.microsoft.com/de-de/dotnet/api/microsoft.visualbasic?view=net-5.0" target="_blank" rel="noreferrer noopener">Microsoft.VisualBasic</a></strong>-Namespace und <strong>benötigt </strong>einen <strong>Verweis </strong>auf die <strong>Microsoft.VisualBasic.Core.dll</strong></p>



<p>In <strong>diesem </strong>konkreten <strong>Fall </strong>benutzen wir für die finale Lösung einfach einen <strong>Escape-Character</strong> für die <strong>Anführungszeichen </strong>im <strong>String</strong>.</p>



<h4 class="wp-block-heading">Ein Escape-Character</h4>



<p><strong>Bei </strong>einem <strong>Anführungszeichen in </strong>einem <strong>String </strong>benötigen wir dafür <strong>einfach ein weiteres </strong>Mal ein <strong>Anführungszeichen</strong>.</p>



<p>Das <strong>mag </strong>zwar <strong>verwirrend klingen</strong>, <strong>aber schau </strong>Dir diese <strong>Code</strong>-Zeile hier einfach mal <strong>an</strong>:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Dim message = ""This" stands between quotation marks"</pre>



<p>In dieser Code-Zeile <strong>steht </strong>das <strong>Wort </strong>&#8222;This&#8220; (wie auch hier) zwischen <strong>Anführungszeichen</strong>.</p>



<h2 class="wp-block-heading">Kompletter Code – VB.NET Anführungszeichen in String</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Public Class Form1

    Private Sub btnShowQuotationMarkInString_Click(sender As Object, e As EventArgs) Handles btnShowQuotationMarkInString.Click
        Dim templateName = tbTemplateName.Text.Trim()
        If String.IsNullOrEmpty(templateName) Then
            MessageBox.Show("Please enter a template name", "Template search", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            Return
        End If

        Dim exampleMessage = $"Could not find template ""{templateName}"" inside the folder"

        ' or without string interpolation
        ' Dim exampleMessage = $"Could not find template """ &amp; templateName &amp; """ inside the folder"

        ' DONT
        ' Dim exampleMessage = $"Could not find template {Chr(34)}{templateName}{Chr(34)} inside the folder"

        MessageBox.Show(exampleMessage, "Template not found", MessageBoxButtons.OK, MessageBoxIcon.Information)
    End Sub

End Class
</pre>



<h2 class="wp-block-heading">Downloads</h2>



<div class="wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link" href="/downloads/vbnet/QuotationMarkInStringExample.zip" target="_blank" rel="noreferrer noopener">QuotationMarkInStringExample.zip</a></div>
</div>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vbnet-anfuehrungszeichen-in-string/">VB.NET Anführungszeichen in String</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/vbnet-anfuehrungszeichen-in-string/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>VB.NET Textdatei schreiben – WriteAllText, Encoding (2026)</title>
		<link>https://robbelroot.de/blog/vbnet-textdatei-schreiben/</link>
					<comments>https://robbelroot.de/blog/vbnet-textdatei-schreiben/#comments</comments>
		
		<dc:creator><![CDATA[Robert Skibbe]]></dc:creator>
		<pubDate>Sat, 10 Jul 2021 10:57:52 +0000</pubDate>
				<category><![CDATA[Allgemein]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Visual Basic .NET]]></category>
		<category><![CDATA[create]]></category>
		<category><![CDATA[datei]]></category>
		<category><![CDATA[erstellen]]></category>
		<category><![CDATA[file]]></category>
		<category><![CDATA[filesystem]]></category>
		<category><![CDATA[io]]></category>
		<category><![CDATA[make]]></category>
		<category><![CDATA[schreiben]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[text]]></category>
		<category><![CDATA[textdatei]]></category>
		<category><![CDATA[txt]]></category>
		<category><![CDATA[vb.net]]></category>
		<category><![CDATA[vbnet]]></category>
		<category><![CDATA[write]]></category>
		<guid isPermaLink="false">https://robbelroot.de/?p=3446</guid>

					<description><![CDATA[<p>Mit File.WriteAllText schreibst du in VB.NET eine Textdatei in wenigen Zeilen. In diesem Beitrag siehst du die einfache Variante, das Schreiben mit UTF-8 Encoding, die asynchrone Version ab .NET 5 und ein praktisches Anwendungsbeispiel mit Konfigurationsdateien – mit komplettem Beispielcode. Willst du stattdessen eine Textdatei einlesen? → VB.NET Textdatei einlesen. Code &#8211; &#8230;</p>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vbnet-textdatei-schreiben/">VB.NET Textdatei schreiben – WriteAllText, Encoding (2026)</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p>Mit <code>File.WriteAllText</code> schreibst du in VB.NET eine Textdatei in wenigen Zeilen. In diesem Beitrag siehst du die einfache Variante, das Schreiben mit UTF-8 Encoding, die asynchrone Version ab .NET 5 und ein praktisches Anwendungsbeispiel mit Konfigurationsdateien – mit komplettem Beispielcode.</p>



<p>Willst du stattdessen eine Textdatei einlesen? → <strong><a href="https://robbelroot.de/blog/vbnet-textdatei-einlesen/" type="post" id="3369" target="_blank" rel="noreferrer noopener">VB.NET Textdatei einlesen</a></strong>.</p>


<div style="box-sizing:border-box;margin:36px 0;border-radius:12px;overflow:hidden;background:#1a1a2e;position:relative;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
  <div style="position:absolute;inset:0;background-image:linear-gradient(rgba(255,255,255,0.03) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,0.03) 1px,transparent 1px);background-size:40px 40px;pointer-events:none;"></div>
  <div style="position:absolute;top:-60px;right:-60px;width:240px;height:240px;background:radial-gradient(circle,rgba(230,126,34,0.18) 0%,transparent 70%);pointer-events:none;"></div>
  <div style="position:relative;padding:32px 28px;">

        <div style="display:inline-block;font-size:11px;font-weight:700;letter-spacing:2.5px;text-transform:uppercase;color:#e67e22;margin-bottom:14px;border:1px solid rgba(230,126,34,0.35);border-radius:4px;padding:3px 10px;">Auftrag?</div>
    
        <p style="margin:0 0 10px 0;font-size:clamp(17px,4vw,21px);font-weight:700;color:#ffffff;line-height:1.35;">VB.NET-Entwicklung für dein Projekt?</p>
    
        <p style="margin:0 0 24px 0;font-size:14px;color:rgba(255,255,255,0.65);line-height:1.7;max-width:540px;">Ich entwickle täglich mit VB.NET und C#. Ob Dateioperationen oder komplette Anwendungen – schreib mir einfach.</p>
    
    <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:center;">

            <a href="https://robbelroot.de/kontakt/"
         style="display:inline-block;padding:12px 24px;background:#e67e22;color:#ffffff;font-size:14px;font-weight:700;text-decoration:none;border-radius:7px;letter-spacing:0.3px;transition:background .2s ease;white-space:nowrap;"
         onmouseover="this.style.background='#cf6d17'"
         onmouseout="this.style.background='#e67e22'"
      >→ Projekt anfragen</a>
      
      
    </div>
  </div>
</div>
	





<h2 class="wp-block-heading">Code &#8211; VB.NET Textdatei schreiben</h2>



<p>Gestalte Dir für den folgenden Schritt am besten eine ähnliche Oberfläche wie die hier drunter und im Anschluss legen wir mit dem Code los:</p>



<figure class="wp-block-image size-large"><a href="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Textdatei-erstellen-GUI.png"><img loading="lazy" decoding="async" width="330" height="382" src="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Textdatei-erstellen-GUI.png" alt="VB.NET Textdatei erstellen GUI" class="wp-image-3427" title="VB.NET Textdatei erstellen GUI" srcset="https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Textdatei-erstellen-GUI.png 330w, https://robbelroot.de/wp-content/uploads/2021/07/VB.NET-Textdatei-erstellen-GUI-259x300.png 259w" sizes="auto, (max-width: 330px) 100vw, 330px" /></a></figure>



<h3 class="wp-block-heading">Datei schreiben</h3>



<h4 class="wp-block-heading">Erforderliche Klassen und Methoden</h4>



<p>Die Möglichkeit zur Erstellung, bzw. Schreiben, Lesen und anderen <strong>dateibezogene Operationen </strong>finden wir in der <strong><a href="https://docs.microsoft.com/de-de/dotnet/api/system.io.file?view=net-5.0" target="_blank" rel="noreferrer noopener">File-Klasse</a></strong>. Wenn man in der .NET Framework Dokumentation nach unserem benötigten Begriff &#8222;write&#8220; sucht, findet man folgende aktuell wichtige Methoden:</p>



<h5 class="wp-block-heading">WriteAllText(filepath, contents)</h5>



<p>Diese Methode schreibt die übergebenen Zeichen in eine Textdatei in den angegebenen Dateipfad. Wenn die Datei nicht schon existiert, wird sie erstellt und andernfalls überschrieben.</p>



<h5 class="wp-block-heading">WriteAllText(filepath, contents, encoding)</h5>



<p>Hier passiert alles analog zur Methode oben, allerdings wird in diesem Fall das Encoding ausdrücklich angegeben.</p>



<h5 class="wp-block-heading">WriteAllTextAsync(filepath, contents, cancellationToken)</h5>



<p>Diese Methode ist noch relativ neu und steht erst in eurem Projekt ab dem .NET 5 Framework zur Verfügung. Besonders bei großen, bzw. größeren Dateien zeigt diese Methode ihre Vorteile durch den asynchronen Dateizugriff.</p>



<h4 class="wp-block-heading">Los geht&#8217;s</h4>



<p>Gehe nun z. B. über den Form-Designer und einem Doppelklick auf den Button in den Ereignishandler für das Button Klick-Ereignis.</p>



<p>Die Datei können wir dann wie folgt in unserem Handler erstellen, bzw. schreiben:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">    Private Sub btnWriteFile_Click(sender As Object, e As EventArgs) Handles btnWriteFile.Click
        Dim filepath = tbFilepath.Text.Trim()
        Dim content = tbContent.Text

        WriteFileSync(filepath, content)
        ' WriteFileWithEncodingSync(filepath, content)
        ' WriteFileAsync(filepath, content)
    End Sub</pre>



<p>Im ersten Schritt hole ich mir den Dateipfad für die geplante Datei und entferne eventuelle Leerzeichen am Anfang und Ende. Den Inhalt der zu erstellenden Datei legen wir in die Variable &#8222;content&#8220;, der dem Text der &#8222;tbContent&#8220;-Textbox entspringt. Im letzten Schritt beginne ich dann mit dem Schreiben der Textdatei, dazu habe ich verschiedene weitere Methoden angelegt.</p>



<h4 class="wp-block-heading">WriteFileSync(filepath, content)</h4>



<p>Hier findet die wohl simpelste Variante statt, Text in eine Textdatei zu schreiben. Wir führen die &#8222;<a href="https://docs.microsoft.com/de-de/dotnet/api/system.io.file.writealltext?view=net-5.0" target="_blank" rel="noreferrer noopener"><strong>WriteAllText</strong></a>&#8222;-Methode der <a href="https://docs.microsoft.com/de-de/dotnet/api/system.io.file?view=net-5.0" target="_blank" rel="noreferrer noopener"><strong>File</strong></a>-Klasse mit passenden Parameter wie den Dateipfad und den zu schreibenden Zeichen, sprich dem Inhalt aus. Den Schreibvorgang selbst habe ich mit einem &#8222;Try Catch&#8220;-Block zum Abfangen globaler Fehler verziert.</p>



<h4 class="wp-block-heading">WriteFileWithEncodingSync(filepath, content)</h4>



<p>Neben unserer Angabe eines expliziten <a href="https://docs.microsoft.com/de-de/dotnet/api/system.text.encoding?view=net-5.0" target="_blank" rel="noreferrer noopener"><strong>Encodings</strong></a> passiert hier nichts anderes als im Beispiel hier drüber.</p>



<h4 class="wp-block-heading">WriteFileAsync(filepath, content)</h4>



<p>Dies ist die oben bereits angesprochene neue Variante, eine Datei zu schreiben, ansonsten identisch mit der ersten Methode &#8222;WriteFileSync&#8220;.</p>



<h2 class="wp-block-heading">Anwendungsbeispiele</h2>



<p>Ein praktisches Anwendungsbeispiel: das Speichern und Laden von Konfigurationsdateien im .ini-Format.</p>



<h3 class="wp-block-heading">Konfigurationsdateien speichern/laden</h3>



<figure class="wp-block-image size-full"><a href="https://robbelroot.de/wp-content/uploads/2021/09/Ini-Dateien-Konfigurationsdateien.jpg"><img loading="lazy" decoding="async" width="640" height="360" src="https://robbelroot.de/wp-content/uploads/2021/09/Ini-Dateien-Konfigurationsdateien.jpg" alt="Textdatei schreiben – Ini-Dateien Konfigurationsdateien" class="wp-image-5934" title="Textdatei schreiben – Ini-Dateien Konfigurationsdateien"/></a><figcaption class="wp-element-caption">Textdatei schreiben – Ini-Dateien Konfigurationsdateien</figcaption></figure>



<p>Ini-Dateien (.ini) sind ein einfaches Format zum Speichern von Schlüssel-Wert-Paaren und eignen sich gut als leichtgewichtige Konfiguration für Desktop-Anwendungen.</p>



<h4 class="wp-block-heading">IniFile-Klasse</h4>



<p>Im ersten Schritt erstellen wir uns eine sehr einfache und rudimentäre IniFile-Klasse. Diese dient der Veranschaulichung, wie man im Ini-Format eine Textdatei schreibt und wieder ausliest. Neben dem Dateinamen, dem Verzeichnis und dem daraus resultierenden Dateipfad besitzt das Ini-File auch einen Namen.</p>



<p>Für <strong>Verbesserungen </strong>würde mir <strong>unter anderem </strong>die Verwendung verschiedener <a href="https://docs.microsoft.com/de-de/dotnet/api/system.text.encoding?view=net-5.0" target="_blank" rel="noreferrer noopener"><strong>Encodings</strong></a> und <a href="https://docs.microsoft.com/de-de/dotnet/visual-basic/programming-guide/concepts/serialization/" target="_blank" rel="noreferrer noopener"><strong>Serializer</strong> </a>einfallen.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="inifile-class">Imports System.IO

Public Class IniFile

    ''' &lt;summary>
    ''' Gets or Sets the path to the directory, containing the file
    ''' &lt;/summary>
    Public Property Directory As String

    ''' &lt;summary>
    ''' Gets or Sets the filename of the file
    ''' &lt;/summary>
    Public Property FileName As String

    ''' &lt;summary>
    ''' Returns the complete path to the ini file
    ''' &lt;/summary>
    Public ReadOnly Property FilePath As String
        Get
            Return Path.Combine(Directory, FileName)
        End Get
    End Property

    Public Property Sections As List(Of IniFileSection)

    Sub New()
        Sections = New List(Of IniFileSection)
    End Sub

    Public Async Function Save() As Task
        Dim contents = ToIniFileString()
        Await File.WriteAllTextAsync(FilePath, contents)
    End Function

    Public Shared Async Function Load(filePath As String) As Task(Of IniFile)
        Dim fileParts = filePath.Split("\")
        Dim iniFile = New IniFile()
        iniFile.Directory = String.Join("\", fileParts.Take(fileParts.Length - 1))
        iniFile.FileName = fileParts.Last()
        Dim contents = Await File.ReadAllTextAsync(filePath)
        Dim nonEmptyLines = contents.Split(Environment.NewLine).Where(Function(x) Not String.IsNullOrWhiteSpace(x))

        ' = nothing is a worarkound for "could be nothing" warning - #irony
        Dim currentSection As IniFileSection = Nothing
        For Each line In nonEmptyLines
            Dim isNewSection = line.StartsWith("[") AndAlso line.EndsWith("]")
            If isNewSection Then
                Dim sectionName = line.Replace("[", "]").Replace("]", "")
                currentSection = New IniFileSection(sectionName)
                iniFile.Sections.Add(currentSection)
                Continue For
            End If

            Dim isNewEntry = line.Contains("=")
            If isNewEntry Then
                Dim entryParts = line.Split("=")
                Dim key = entryParts(0)
                Dim value = entryParts(1)
                Dim entry = New IniFileSectionEntry(key, value)
                currentSection.Entries.Add(entry)
                Continue For
            End If
        Next
        Return iniFile
    End Function

    Public Function ToIniFileString() As String
        Dim sectionStrings = New List(Of String)
        For Each section In Sections
            sectionStrings.Add(section.ToIniFileString())
        Next
        Return String.Join(Environment.NewLine, sectionStrings)
    End Function

    Public Overrides Function ToString() As String
        Return $"IniFile: {FilePath}"
    End Function

End Class
</pre>



<h4 class="wp-block-heading">IniFileSection-Klasse</h4>



<p>Als nächstes kommt die IniFileSection-Klasse, die neben dem Namen der Sektion auch dessen Einträge beinhaltet.</p>



<p>Die gesamten Daten können wir dann mit Hilfe der kleinen Helper-Methode namens &#8222;ToIniFileString&#8220; bekommen.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="inifilesection-class">Public Class IniFileSection

    Public Property Name As String

    Public Property Entries As List(Of IniFileSectionEntry)

    Sub New(name As String)
        Me.Name = name
        Entries = New List(Of IniFileSectionEntry)
    End Sub

    Public Function ToIniFileString() As String
        Dim str = $"[{Name}]"
        For Each entry In Entries
            str &amp;= $"{Environment.NewLine}{entry.ToIniFileString()}"
        Next
        Return str
    End Function

    Public Overrides Function ToString() As String
        Return $"IniFileSection: {Name}"
    End Function

End Class
</pre>



<h4 class="wp-block-heading">IniFileSectionEntry-Klasse</h4>



<p>Zum Schluss kommt die IniFileSectionEntry-Klasse, die den Schlüssel und den dahinter stehenden Wert beinhaltet. Sie hat die gleichnamige Helper-Funktion, um den Eintrag ini-konform umzuwandeln.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="inifilesectionentry-class">Public Class IniFileSectionEntry

    Public Property Key As String

    Public Property Value As String

    Sub New()
        Key = ""
        Value = ""
    End Sub

    Sub New(key As String, value As String)
        Me.Key = key
        Me.Value = value
    End Sub

    Public Function ToIniFileString() As String
        Return $"{Key}={Value}"
    End Function

    Public Overrides Function ToString() As String
        Return $"IniFileSectionEntry: {Key}={Value}"
    End Function

End Class</pre>



<h4 class="wp-block-heading">Verwendungsbeispiel in einer Konsolenanwendung</h4>



<p>Zu guter Letzt kommt das Modul für die Konsole, worin wir 1-2 Beispiel-Aufrufe durchführen. Lade Dir bei Bedarf eines des Beispielprojekte herunter, dann kannst Du Dir das Ganze im Detail ansehen.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="VB.NET" data-enlighter-group="module">Module Program

    Sub Main(args As String())
        Console.Title = "TextFileCreateIniFile"
        DoExampleReadWrite()
    End Sub

    Public Async Sub DoExampleReadWrite()
        ' A
        ' put the config file into the same directory as the exe file
        ' or change the path
        Dim ini = Await IniFile.Load(".\example-config.ini")
        Console.WriteLine("Press Enter to overwrite the first sections, first entries value with TEST")
        Console.ReadLine()
        ini.Sections(0).Entries(0).Value = "TEST"
        Console.WriteLine("Press Enter to save the changes to file")
        Console.ReadLine()
        Await ini.Save()
        Console.WriteLine("File saved, press enter to leave")
        Console.ReadLine()
    End Sub

End Module
</pre>


<div style="box-sizing:border-box;margin:36px 0;border-radius:12px;overflow:hidden;background:#1a1a2e;position:relative;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;">
  <div style="position:absolute;inset:0;background-image:linear-gradient(rgba(255,255,255,0.03) 1px,transparent 1px),linear-gradient(90deg,rgba(255,255,255,0.03) 1px,transparent 1px);background-size:40px 40px;pointer-events:none;"></div>
  <div style="position:absolute;top:-60px;right:-60px;width:240px;height:240px;background:radial-gradient(circle,rgba(230,126,34,0.18) 0%,transparent 70%);pointer-events:none;"></div>
  <div style="position:relative;padding:32px 28px;">

        <div style="display:inline-block;font-size:11px;font-weight:700;letter-spacing:2.5px;text-transform:uppercase;color:#e67e22;margin-bottom:14px;border:1px solid rgba(230,126,34,0.35);border-radius:4px;padding:3px 10px;">Interessiert?</div>
    
        <p style="margin:0 0 10px 0;font-size:clamp(17px,4vw,21px);font-weight:700;color:#ffffff;line-height:1.35;">VB.NET-Entwicklung für dein Projekt?</p>
    
        <p style="margin:0 0 24px 0;font-size:14px;color:rgba(255,255,255,0.65);line-height:1.7;max-width:540px;">Ich entwickle täglich mit VB.NET und C#. Ob Dateioperationen oder komplette Anwendungen – schreib mir einfach.</p>
    
    <div style="display:flex;flex-wrap:wrap;gap:12px;align-items:center;">

            <a href="https://robbelroot.de/kontakt/"
         style="display:inline-block;padding:12px 24px;background:#e67e22;color:#ffffff;font-size:14px;font-weight:700;text-decoration:none;border-radius:7px;letter-spacing:0.3px;transition:background .2s ease;white-space:nowrap;"
         onmouseover="this.style.background='#cf6d17'"
         onmouseout="this.style.background='#e67e22'"
      >→ Projekt anfragen</a>
      
      
    </div>
  </div>
</div>
	


<div class="schema-faq wp-block-yoast-faq-block"><div class="schema-faq-section" id="faq-question-1775568532495"><strong class="schema-faq-question">Wie schreibe ich eine Textdatei in VB.NET?</strong> <p class="schema-faq-answer">Verwende <code>File.WriteAllText(filepath, content)</code> aus dem Namespace <code>System.IO</code>. Die Methode erstellt die Datei, wenn sie nicht existiert, und überschreibt sie andernfalls.</p> </div> <div class="schema-faq-section" id="faq-question-1775568624004"><strong class="schema-faq-question">Wie schreibe ich eine Textdatei mit UTF-8 Encoding in VB.NET?</strong> <p class="schema-faq-answer">Übergib das Encoding als dritten Parameter: <code>File.WriteAllText(filepath, content, System.Text.Encoding.UTF8)</code>. Das stellt sicher, dass Sonderzeichen wie Umlaute korrekt gespeichert werden.</p> </div> <div class="schema-faq-section" id="faq-question-1775568627767"><strong class="schema-faq-question">Gibt es eine asynchrone Methode zum Schreiben in VB.NET?</strong> <p class="schema-faq-answer">Ja. Ab .NET 5 steht <code>Await File.WriteAllTextAsync(filepath, content)</code> zur Verfügung. Sie ist besonders bei größeren Dateien sinnvoll, um den UI-Thread nicht zu blockieren.</p> </div> <div class="schema-faq-section" id="faq-question-1775568634355"><strong class="schema-faq-question">Wird eine bestehende Datei überschrieben oder angehängt?</strong> <p class="schema-faq-answer"><code>WriteAllText</code> überschreibt eine bestehende Datei vollständig. Willst du Inhalt anhängen statt überschreiben, verwende stattdessen <code>File.AppendAllText(filepath, content)</code>.</p> </div> </div>



<h2 class="wp-block-heading">Kompletter Code – VB.NET Textdatei schreiben</h2>



<pre class="EnlighterJSRAW" data-enlighter-language="visualbasic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">Imports System.IO

Public Class Form1

    Private Sub btnWriteFile_Click(sender As Object, e As EventArgs) Handles btnWriteFile.Click
        Dim filepath = tbFilepath.Text.Trim()
        Dim content = tbContent.Text

        WriteFileSync(filepath, content)
        ' WriteFileWithEncodingSync(filepath, content)
        ' WriteFileAsync(filepath, content)
    End Sub

    Private Sub WriteFileSync(filepath As String, content As String)
        Try
            File.WriteAllText(filepath, content)
        Catch ex As Exception
            MessageBox.Show("Couldn't write file sync: " &amp; ex.Message)
        End Try
    End Sub

    Private Sub WriteFileWithEncodingSync(filepath As String, content As String)
        Dim encoding = System.Text.Encoding.UTF8
        Try
            File.WriteAllText(filepath, content, encoding)
        Catch ex As Exception
            MessageBox.Show("Couldn't write file sync with encoding: " &amp; ex.Message)
        End Try
    End Sub

    ' only available with .NET 5
    ' not in .NET Framework Apps
    'Private Sub WriteFileAsync(filepath As String, content As String)
    '    Try
    '        File.WriteAllTextAsync(filepath, content)
    '    Catch ex As Exception
    '        MessageBox.Show("Couldn't write file async: " &amp; ex.Message)
    '    End Try
    'End Sub

End Class</pre>



<h2 class="wp-block-heading">Downloads</h2>



<div class="wp-block-buttons is-layout-flex wp-block-buttons-is-layout-flex">
<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="/downloads/vbnet/WriteTextFileExample.zip" target="_blank" rel="noreferrer noopener">WriteTextFileExample.zip</a></div>



<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="https://robbelroot.de/downloads/vbnet/TextFileCreateIniFileVB.zip" target="_blank" rel="noreferrer noopener">TextFileCreateIniFileVB.zip</a></div>
</div>
<p>Der Beitrag <a href="https://robbelroot.de/blog/vbnet-textdatei-schreiben/">VB.NET Textdatei schreiben – WriteAllText, Encoding (2026)</a> erschien zuerst auf <a href="https://robbelroot.de">Robert Skibbe</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://robbelroot.de/blog/vbnet-textdatei-schreiben/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
	</channel>
</rss>
