Monthly Archives: December 2020
C++ || How To Get A List Of Files At A Given Path Directory Using C++

The following is a module with functions which demonstrates how to get a list of files at a given directory path using C++.
The function demonstrated on this page returns a list of std::filesystem::directory_entry, which contains information about the files in the given directory.
1. Get Files In Directory
The example below demonstrates the use of ‘Utils::getFilesInDirectory‘ to get a list of files at a given path directory.
The optional function parameter lets you specify the search option. Set the search option to True to limit the search to just the current directory. Set the search option to False to expand the search to the current directory and all subdirectories when searching for files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Get Files In Directory // Declare path std::string directory = "C:\\Users\\Name\\Desktop"; // Get files at the specified directory auto files = Utils::getFilesInDirectory(directory); // Display info about the files for (const auto& file : files) { std::cout << "File: " << file.path().u8string() << std::endl; } // example output: /* File: C:\Users\Name\Desktop\text.txt File: C:\Users\Name\Desktop\image.png File: C:\Users\Name\Desktop\document.docx */ |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 8, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <vector> #include <filesystem> namespace Utils { /** * FUNCTION: getFilesInDirectory * USE: Returns a 'directory_entry' list of the files in the given directory * @param directory: The relative or absolute path to the directory to search * @param topDirectoryOnly: If True, limits the search to just the current * directory. If False, expands the search to the current directory * and all subdirectories * @return: A list of 'directory_entry' in the given directory */ auto getFilesInDirectory(const std::string& directory, bool topDirectoryOnly = true) { namespace fs = std::filesystem; std::vector<fs::directory_entry> results; auto fill = [&results](const auto& iter) { for (const fs::directory_entry& entry : iter) { if (!entry.is_regular_file()) { continue; } results.push_back(entry); } }; if (topDirectoryOnly) { fill(fs::directory_iterator(directory)); } else { fill(fs::recursive_directory_iterator(directory)); } return results; } }// http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 8, 2020 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ #include <iostream> #include <string> #include <exception> #include "Utils.h" void display(const std::string& message); int main() { try { // Declare path std::string directory = "C:\\Users\\Name\\Desktop"; // Get files at the specified directory auto files = Utils::getFilesInDirectory(directory); // Display info about the files for (const auto& file : files) { std::cout << "File: " << file.path().u8string() << std::endl; } } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C++ || How To Make Map & Unordered Map Keys Case Insensitive Using C++

The following is a module with functions which demonstrates how to make map and unordered_map keys case insensitive using C++.
1. Case Insensitive – Map
The example below demonstrates how to make a map with a string key case insensitive.
To do this, the comparison function needs to be overridden.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// Case Insensitive - Map #include <string> #include <map> // Makes map keys case insensitive struct case_insensitive_map { struct comp { bool operator() (const std::string& lhs, const std::string& rhs) const { // On non Windows OS, use the function "strcasecmp" in #include <strings.h> return _stricmp(lhs.c_str(), rhs.c_str()) < 0; } }; }; // Declare map std::map<std::string, unsigned, case_insensitive_map::comp> map = { {"KENNetH", 2019}, {"Jennifer", 2010}, {"Lynn", 28}, {"SOLe", 31} }; // Display results std::cout << map["kenneth"] << ", " << map["JeNniFer"] << ", " << map["LYNN"] << ", " << map["sole"]; // expected output: /* 2019, 2010, 28, 31 */ |
2. Case Insensitive – Unordered Map
The example below demonstrates how to make an unordered map with a string key case insensitive.
To do this, the comparison and the hash function needs to be overridden.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
// Case Insensitive - Unordered Map #include <string> #include <unordered_map> #include <utility> #include <cctype> // Makes unordered map keys case insensitive struct case_insensitive_unordered_map { struct comp { bool operator() (const std::string& lhs, const std::string& rhs) const { // On non Windows OS, use the function "strcasecmp" in #include <strings.h> return _stricmp(lhs.c_str(), rhs.c_str()) == 0; } }; struct hash { std::size_t operator() (std::string str) const { for (std::size_t index = 0; index < str.size(); ++index) { auto ch = static_cast<unsigned char>(str[index]); str[index] = static_cast<unsigned char>(std::tolower(ch)); } return std::hash<std::string>{}(str); } }; }; // Declare unordered map std::unordered_map<std::string, unsigned , case_insensitive_unordered_map::hash , case_insensitive_unordered_map::comp> unorderedMap = { {"KENNetH", 2019}, {"Jennifer", 2010}, {"Lynn", 28}, {"SOLe", 31} }; // Display results std::cout << unorderedMap["kenneth"] << ", " << unorderedMap["JeNniFer"] << ", " << unorderedMap["LYNN"] << ", " << unorderedMap["sole"]; // expected output: /* 2019, 2010, 28, 31 */ |
3. Full Examples
Below is a full example demonstrating the concepts on this page.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 8, 2020 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates case insensitive maps. // ============================================================================ #include <iostream> #include <string> #include <exception> #include <map> #include <unordered_map> #include <utility> #include <cctype> void display(const std::string& message); // Makes map keys case insensitive struct case_insensitive_map { struct comp { bool operator() (const std::string& lhs, const std::string& rhs) const { // On non Windows OS, use the function "strcasecmp" in #include <strings.h> return _stricmp(lhs.c_str(), rhs.c_str()) < 0; } }; }; // Makes unordered map keys case insensitive struct case_insensitive_unordered_map { struct comp { bool operator() (const std::string& lhs, const std::string& rhs) const { // On non Windows OS, use the function "strcasecmp" in #include <strings.h> return _stricmp(lhs.c_str(), rhs.c_str()) == 0; } }; struct hash { std::size_t operator() (std::string str) const { for (std::size_t index = 0; index < str.size(); ++index) { auto ch = static_cast<unsigned char>(str[index]); str[index] = static_cast<unsigned char>(std::tolower(ch)); } return std::hash<std::string>{}(str); } }; }; int main() { try { // Declare map std::map<std::string, unsigned, case_insensitive_map::comp> map = { {"KENNetH", 2019}, {"Jennifer", 2010}, {"Lynn", 28}, {"SOLe", 31} }; // Display results std::cout << map["kenneth"] << ", " << map["JeNniFer"] << ", " << map["LYNN"] << ", " << map["sole"]; display(""); // Declare unordered map std::unordered_map<std::string, unsigned , case_insensitive_unordered_map::hash , case_insensitive_unordered_map::comp> unorderedMap = { {"KENNetH", 2019}, {"Jennifer", 2010}, {"Lynn", 28}, {"SOLe", 31} }; // Display results std::cout << unorderedMap["kenneth"] << ", " << unorderedMap["JeNniFer"] << ", " << unorderedMap["LYNN"] << ", " << unorderedMap["sole"]; } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C++ || How To Search For & Find A Specific Element In A Vector Using C++

The following is a module with functions which demonstrates how to search for and find a specific element in a vector using C++.
The function demonstrated on this page is a template, so it should work on vectors of any type. It also uses a predicate to determine the item to select.
1. Find
The example below demonstrates the use of ‘Utils::find‘ to find the first element in a sequence of values based on a predicate.
The predicate determines the item to find.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Find // Declare vector std::vector<std::string> names = { "Kenneth", "Jennifer", "Lynn", "Sole" }; // Declare predicate auto predicate = [](const auto& x) { return x.size() >= 8; }; // Get the result auto name = Utils::find(names, predicate); // Display the result std::cout << "Name: " << (*name); // expected output: /* Name: Jennifer */ |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 8, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <vector> #include <algorithm> #include <iterator> namespace Utils { /** * FUNCTION: find * USE: Returns the first element in the given range [first, last) based on a predicate * @param first: The first position of the sequence * @param last: The last position of the sequence * @param predicate: A function to test each element for a condition * @return: A Pointer to the first element that satisfies the predicate, nullptr otherwise */ template<typename RandomIt, typename T = typename std::iterator_traits<RandomIt>::value_type, typename Pred> T* find(RandomIt first, RandomIt last, const Pred& predicate) { T* result = nullptr; auto iter = std::find_if(first, last, predicate); if (iter != last) { result = &(*iter); } return result; } /** * FUNCTION: find * USE: Returns the first element in the collection based on a predicate * @param source: The collection to find items * @param predicate: A function to test each element for a condition * @return: A Pointer to the first element that satisfies the predicate, nullptr otherwise */ template<typename T, typename Pred> T* find(std::vector<T>& source, const Pred& predicate) { return find<typename std::vector<T>::iterator, T, Pred>(source.begin(), source.end(), predicate); } }// http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 8, 2020 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ #include <iostream> #include <string> #include <exception> #include <vector> #include "Utils.h" void display(const std::string& message); int main() { try { // Declare vector std::vector<std::string> names = { "Kenneth", "Jennifer", "Lynn", "Sole" }; // Declare predicate auto predicate = [](const auto& x) { return x.size() >= 8; }; // Get the result auto name = Utils::find(names, predicate); // Display the result display("Name: " + (*name)); } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C++ || How To Filter & Select Items In An Array/Vector/Container & Get The Results Using C++

The following is a module with functions which demonstrates how to filter and select items in an array/vector/container, and get the results using C++.
The function demonstrated on this page is a template, so it should work on containers of any type. It also uses a predicate to determine the items to select.
1. Filter – Integer Array
The example below demonstrates the use of ‘Utils::filter‘ to filter an integer array based on a predicate and return its results.
The predicate determines the items to filter and select.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Filter - Integer Array // Declare numbers int numbers[] = { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; // Get array size int size = sizeof(numbers) / sizeof(numbers[0]); // Declare predicate auto predicate = [](const auto& x) { return x == 1987 || x == 1991; }; // Get results auto results = Utils::filter(numbers, numbers + size, predicate); // Display the results for (const auto& number : results) { std::cout << "Number: " << number << std::endl; } // expected output: /* Number: 1987 Number: 1991 */ |
2. Filter – String Vector
The example below demonstrates the use of ‘Utils::filter‘ to filter a sequence of values based on a predicate and return its results.
The predicate determines the items to filter and select.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Filter - String Vector // Declare vector std::vector<std::string> names = { "Kenneth", "Jennifer", "Lynn", "Sole" }; // Declare predicate auto predicate = [](const auto& x) { return x == "Kenneth" || x == "Jennifer"; }; // Get the results auto results = Utils::filter(names.begin(), names.end(), predicate); // Display the results for (const auto& name : results) { std::cout << "Name: " << name << std::endl; } // expected output: /* Name: Kenneth Name: Jennifer */ |
3. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 8, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <vector> #include <algorithm> #include <iterator> namespace Utils { /** * FUNCTION: filter * USE: Filters a sequence of values in the given range [first, last) * based on a predicate and returns its results * @param first: The first position of the sequence * @param last: The last position of the sequence * @param predicate: A function to test each element for a condition * @return: A collection that contains elements from the input * sequence that satisfies the condition */ template<typename InputIt, typename T = typename std::iterator_traits<InputIt>::value_type, typename Pred> std::vector<T> filter(InputIt first, InputIt last, const Pred& predicate) { std::vector<T> result; std::copy_if(first, last, std::back_inserter(result), predicate); return result; } }// http://programmingnotes.org/ |
4. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 8, 2020 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ #include <iostream> #include <string> #include <exception> #include <vector> #include "Utils.h" void display(const std::string& message); int main() { try { // Declare numbers int numbers[] = { 1987, 19, 22, 2009, 2019, 1991, 28, 31 }; // Get array size int size = sizeof(numbers) / sizeof(numbers[0]); // Declare predicate auto predicate = [](const auto& x) { return x == 1987 || x == 1991; }; // Get results auto results = Utils::filter(numbers, numbers + size, predicate); // Display the results for (const auto& number : results) { display("Number: " + std::to_string(number)); } display(""); // Declare vector std::vector<std::string> names = { "Kenneth", "Jennifer", "Lynn", "Sole" }; // Declare predicate auto predicate2 = [](const auto& x) { return x == "Kenneth" || x == "Jennifer"; }; // Get the results auto results2 = Utils::filter(names.begin(), names.end(), predicate2); // Display the results for (const auto& name : results2) { display("Name: " + name); } } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C++ || How To Check If An Item Exists In A Vector And Get Its Position Index Using C++

The following is a module with functions which demonstrates how to find the position index of an item in a vector, and make sure the item exists using C++.
The functions demonstrated on this page are wrappers for std::find_if function, and are templates, so they should work on vectors/containers of any type.
1. Contains
The example below demonstrates the use of ‘Utils::contains‘ to determine whether an element is contained in the collection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Contains // Declare vector std::vector<std::string> names = {"Kenneth", "Jennifer", "Lynn", "Sole"}; // Declare names to search std::string searches[] = {"Lynn", "Jessica"}; // Display results for (const auto& name : searches) { std::cout << "Name: " << name << ", Contains Item: " << (Utils::contains(names, name) ? "True" : "False") << std::endl; } // expected output: /* Name: Lynn, Contains Item: True Name: Jessica, Contains Item: False */ |
2. Index Of
The example below demonstrates the use of ‘Utils::indexOf‘ to get the zero based index of the first occurrence of a search value in the collection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// Index Of // Declare vector std::vector<std::string> names = {"Kenneth", "Jennifer", "Lynn", "Sole"}; // Declare names to search std::string searches[] = {"Lynn", "Jessica"}; // Display results for (const auto& name : searches) { std::cout << "Name: " << name << ", Index: " << Utils::indexOf(names, name) << std::endl; } // expected output: /* Name: Lynn, Index: 2 Name: Jessica, Index: -1 */ |
3. Index Of – Predicate
The example below demonstrates the use of ‘Utils::indexOf‘ to get the zero based index of the first occurrence of a search value in the collection.
In this example, a predicate is used to determine the item to search for. This allows you to customize how an item should be searched.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Index Of - Predicate // Declare vector std::vector<std::string> names = {"Kenneth", "Jennifer", "Lynn", "Sole"}; // Declare names to search std::string searches[] = {"Lynn", "Jessica"}; // Display results for (const auto& name : searches) { auto pred = [name](const auto& x) { return x == name; }; std::cout << "Name: " << name << ", Index: " << Utils::indexOf(names, pred) << std::endl; } // expected output: /* Name: Lynn, Index: 2 Name: Jessica, Index: -1 */ |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 7, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <vector> #include <algorithm> #include <iterator> namespace Utils { /** * FUNCTION: indexOf * USE: Returns the zero-based index of the first occurrence of a value in * the given range [first, last) * @param first: The first position of the sequence * @param last: The last position of the sequence * @param predicate: A function to test each element for a condition * @return: The zero-based index of the first occurrence, or -1 otherwise */ template<typename InputIt, typename Pred> int indexOf(InputIt first, InputIt last, const Pred& predicate) { auto pos = std::find_if(first, last, predicate); return pos != last ? pos - first : -1; } /** * FUNCTION: indexOf * USE: Returns the zero-based index of the first occurrence of a value * in the collection * @param source: The collection to find items * @param predicate: A function to test each element for a condition * @return: The zero-based index of the first occurrence, or -1 otherwise */ template<typename T, typename Pred> int indexOf(const std::vector<T>& source, const Pred& predicate) { return indexOf(source.begin(), source.end(), predicate); } /** * FUNCTION: indexOf * USE: Returns the zero-based index of the first occurrence of a value * in the collection * @param source: The collection to search * @param search: The item to search for * @return: The zero-based index of the first occurrence, or -1 otherwise */ template<typename T> int indexOf(const std::vector<T>& source, const T& search) { auto pred = [&](const T& x) { return x == search; }; return indexOf(source, pred); } /** * FUNCTION: contains * USE: Determines whether an element is in the given range [first, last) * @param first: The first position of the sequence * @param last: The last position of the sequence * @param predicate: A function to test each element for a condition * @return: True if the item is inside the collection, false otherwise */ template<typename InputIt, typename Pred> bool contains(InputIt first, InputIt last, const Pred& predicate) { return indexOf(first, last, predicate) > -1; } /** * FUNCTION: contains * USE: Determines whether an element is in the collection * @param source: The collection to search * @param predicate: A function to test each element for a condition * @return: True if the item is inside the collection, false otherwise */ template<typename InputIt, typename T = typename std::iterator_traits<InputIt>::value_type, typename Pred> bool contains(const std::vector<T>& source, const Pred& predicate) { return indexOf(source.begin(), source.end(), predicate) > -1; } /** * FUNCTION: contains * USE: Determines whether an element is in the collection * @param source: The collection to search * @param search: The item to search for * @return: True if the item is inside the collection, false otherwise */ template<typename T> bool contains(const std::vector<T>& source, const T& search) { return indexOf(source, search) > -1; } }// http://programmingnotes.org/ |
5. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 7, 2020 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ #include <iostream> #include <string> #include <exception> #include <vector> #include "Utils.h" void display(const std::string& message); int main() { try { // Declare vector std::vector<std::string> names = {"Kenneth", "Jennifer", "Lynn", "Sole"}; // Declare names to search std::string searches[] = {"Lynn", "Jessica"}; // Display results for (const auto& name : searches) { display("Name: " + name + ", Contains Item: " + (Utils::contains(names, name) ? "True" : "False")); } // Display results for (const auto& name : searches) { display("Name: " + name + ", Index: " + std::to_string(Utils::indexOf(names, name))); } // Display results for (const auto& name : searches) { auto pred = [name](const auto& x) { return x == name; }; display("Name: " + name + ", Index: " + std::to_string(Utils::indexOf(names, pred))); } } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C++ || How To Merge & Concatenate Two Vectors Using C++

The following is a module with functions which demonstrates how to merge, concatenate and append two vectors using C++.
The function demonstrated on this page is a template, so it should work on vectors of any type.
1. Add Range
The example below demonstrates the use of ‘Utils::addRange‘ add elements to the end of the collection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Add Range // Declare vector std::vector<std::string> names = {"Kenneth"}; // Add more names Utils::addRange(names, {"Jennifer", "Lynn", "Sole"}); // Display results for (const auto& name : names) { std::cout << "Name: " + name << std::endl; } // expected output: /* Name: Kenneth Name: Jennifer Name: Lynn Name: Sole */ |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 7, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <vector> #include <iterator> namespace Utils { /** * FUNCTION: addRange * USE: Adds elements to the end of the collection * @param source: The collection that will have items added to it * @param addition: The items that should be added to the end of the collection * @return: N/A */ template<typename T> void addRange(std::vector<T>& source, const std::vector<T>& addition) { source.reserve(source.size() + addition.size()); source.insert(source.end() , std::make_move_iterator(addition.begin()) , std::make_move_iterator(addition.end())); } }// http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 7, 2020 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ #include <iostream> #include <string> #include <exception> #include <vector> #include "Utils.h" void display(const std::string& message); int main() { try { // Declare vector std::vector<std::string> names = {"Kenneth"}; // Add more names Utils::addRange(names, {"Jennifer", "Lynn", "Sole"}); // Display results for (const auto& name : names) { display("Name: " + name); } } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C++ || How To Replace All Occurrences Of A String With Another String Using C++

The following is a module with functions which demonstrates how to replace all occurrences of a substring with another substring using C++.
1. Replace All
The example below demonstrates the use of ‘Utils::replaceAll‘ to replace all occurrences of an ‘oldValue’ string with a ‘newValue’ string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Replace All // Declare string std::string numbers = "1987 19 22 2009 2019 1991 28 31"; // Replace whitespace with a comma std::string replaced = Utils::replaceAll(numbers, " ", ", "); // Display the result std::cout << "Original: " << numbers; std::cout << "Replaced: " << replaced; // expected output: /* Original: 1987 19 22 2009 2019 1991 28 31 Replaced: 1987, 19, 22, 2009, 2019, 1991, 28, 31 */ |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 7, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <string> namespace Utils { /** * FUNCTION: replaceAll * USE: Replaces all occurrences of the 'oldValue' string with the * 'newValue' string * @param source: The source string * @param oldValue: The string to be replaced * @param newValue: The string to replace all occurrences of oldValue * @return: A new string with all occurrences replaced */ std::string replaceAll(const std::string& source , const std::string& oldValue, const std::string& newValue) { if (oldValue.empty()) { return source; } std::string newString; newString.reserve(source.length()); std::size_t lastPos = 0; std::size_t findPos; while (std::string::npos != (findPos = source.find(oldValue, lastPos))) { newString.append(source, lastPos, findPos - lastPos); newString += newValue; lastPos = findPos + oldValue.length(); } newString += source.substr(lastPos); return newString; } }// http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 7, 2020 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ #include <iostream> #include <string> #include <exception> #include "Utils.h" void display(const std::string& message); int main() { try { // Declare string std::string numbers = "1987 19 22 2009 2019 1991 28 31"; // Replace whitespace with a comma std::string replaced = Utils::replaceAll(numbers, " ", ", "); // Display the result display("Original: " + numbers); display("Replaced: " + replaced); } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C++ || How To Check If A String Is Empty Or Only Contains Whitespace Using C++

The following is a module with functions which demonstrates how to determine whether a string is empty, or consists only of white-space characters using C++.
1. Is Null Or Whitespace
The example below demonstrates the use of ‘Utils::isNullOrWhitespace‘ to determine whether a string is empty, or consists only of white-space characters.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Is Null Or Whitespace // Declare values std::string words[] = { "Kenneth", "", "Jennifer", " ", "Lynn", "\n\t", "Sole" }; // Check to see which is empty for (auto& word: words) { bool isEmpty = Utils::isNullOrWhitespace(word); std::cout << "Word: " << word << ", Is Empty: " << (isEmpty ? "True" : "False") << std::endl; } // expected output: /* Word: Kenneth, Is Empty: False Word: , Is Empty: True Word: Jennifer, Is Empty: False Word: , Is Empty: True Word: Lynn, Is Empty: False Word: , Is Empty: True Word: Sole, Is Empty: False */ |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 5, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <string> #include <cctype> #include <algorithm> namespace Utils { /** * FUNCTION: isNullOrWhitespace * USE: Indicates whether a specified string is empty, or consists only * of whitespace characters * @param str: The source string * @return: True if str is Empty, or consists of only whitespace characters, * False otherwise */ bool isNullOrWhitespace(const std::string& str) { return str.empty() || std::all_of(str.begin(), str.end(), [](char c) { return std::isspace(static_cast<unsigned char>(c)); }); } }// http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 5, 2020 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ #include <iostream> #include <string> #include <exception> #include "Utils.h" void display(const std::string& message); int main() { try { // Declare values std::string words[] = { "Kenneth", "", "Jennifer", " ", "Lynn", "\n\t", "Sole" }; // Check to see which is empty for (auto& word: words) { bool isEmpty = Utils::isNullOrWhitespace(word); display("Word: " + word + ", Is Empty: " + (isEmpty ? "True" : "False")); } } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C++ || How To Convert A String To Upper and Lower Case Using C++

The following is a module with functions which demonstrates how to convert a string to all upper and lower case using C++.
1. To Upper Case
The example below demonstrates the use of ‘Utils::toUpperCase‘ to convert a string to all upper case.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// To Upper Case // Declare word std::string word = "Kenneth, Jennifer, Lynn, Sole"; // Convert to uppercase auto result = Utils::toUpperCase(word); std::cout << result; // expected output: /* KENNETH, JENNIFER, LYNN, SOLE */ |
2. To Lower Case
The example below demonstrates the use of ‘Utils::toLowerCase‘ to convert a string to all lower case.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// To Lower Case // Declare word std::string word = "Kenneth, Jennifer, Lynn, Sole"; // Convert to lowercase auto result = Utils::toLowerCase(word); std::cout << result; // expected output: /* kenneth, jennifer, lynn, sole */ |
3. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 5, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <string> #include <cctype> #include <algorithm> namespace Utils { /** * FUNCTION: toUpperCase * USE: Converts a string to all uppercase * @param source: The source string * @return: The modified source string */ std::string toUpperCase(std::string source) { std::transform(source.begin(), source.end(), source.begin(), [](unsigned char c) { return static_cast<unsigned char>(std::toupper(c)); }); return source; } /** * FUNCTION: toLowerCase * USE: Converts a string to all lowercase * @param source: The source string * @return: The modified source string */ std::string toLowerCase(std::string source) { std::transform(source.begin(), source.end(), source.begin(), [](unsigned char c) { return static_cast<unsigned char>(std::tolower(c)); }); return source; } }// http://programmingnotes.org/ |
4. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 5, 2020 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ #include <iostream> #include <string> #include <exception> #include "Utils.h" void display(const std::string& message); int main() { try { // Declare word std::string word = "Kenneth, Jennifer, Lynn, Sole"; // Convert to uppercase auto result = Utils::toUpperCase(word); display(result); // Convert to lowercase auto result2 = Utils::toLowerCase(word); display(result2); } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C++ || How To Remove All Whitespace From A String Using C++

The following is a module with functions which demonstrates how to remove all whitespace from a string using C++.
1. Remove All Whitespace
The example below demonstrates the use of ‘Utils::RemoveWhitespace‘ to remove all whitespace from a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Remove All Whitespace // Declare word std::string word = "This document uses 3 other documents "; // Remove whitespace from the string auto result = Utils::removeAllWhitespace(word); std::cout << result; /* expected output: Thisdocumentuses3otherdocuments */ |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 5, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <string> #include <cctype> #include <algorithm> namespace Utils { /** * FUNCTION: removeAllWhitespace * USE: Removes all whitespace from a string * @param source: The source string * @return: The modified source string */ std::string removeAllWhitespace(std::string source) { source.erase(std::remove_if(source.begin(), source.end(), [](char c) { return std::isspace(static_cast<unsigned char>(c)); }), source.end()); return source; } }// http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 5, 2020 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ #include <iostream> #include <string> #include <exception> #include "Utils.h" void display(const std::string& message); int main() { try { // Declare word std::string word = "This document uses 3 other documents "; // Remove whitespace from the string auto result = Utils::removeAllWhitespace(word); display(result); } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
C++ || How To Get The File Path, File Name & File Extension From A Path Using C++

The following is a module with functions which demonstrates how to parse a file path, file name and file extension from a path using C++.
1. Get File Path
The example below demonstrates the use of ‘Utils::getFilePath‘ to parse and get the file path from a path.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Get File Path // Declare path std::string path = "C:\\Users\\Name\\Desktop\\20171216_155433.jpg"; // Get the file path auto filePath = Utils::getFilePath(path); std::cout << "Path: " << path << std::endl; std::cout << "File Path: " << filePath; // expected output: /* Path: C:\Users\Name\Desktop\20171216_155433.jpg File Path: C:\Users\Name\Desktop */ |
2. Get File Name
The example below demonstrates the use of ‘Utils::getFileName‘ to parse and get the file name from a path.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Get File Name // Declare path std::string path = "C:\\Users\\Name\\Desktop\\20171216_155433.jpg"; // Get the file name auto fileName = Utils::getFileName(path); std::cout << "Path: " << path << std::endl; std::cout << "File Name: " << fileName; // expected output: /* Path: C:\Users\Name\Desktop\20171216_155433.jpg File Name: 20171216_155433.jpg */ |
3. Get File Name Extension
The example below demonstrates the use of ‘Utils::getFileExtension‘ to parse and get the file extension from a path.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Get File Name Extension // Declare path std::string path = "C:\\Users\\Name\\Desktop\\20171216_155433.jpg"; // Get the file extension auto extension = Utils::getFileExtension(path); std::cout << "Path: " << path << std::endl; std::cout << "File Extension: " << extension; // expected output: /* Path: C:\Users\Name\Desktop\20171216_155433.jpg File Extension: jpg */ |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 5, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <string> #include <algorithm> #include <cctype> namespace Utils { /** * FUNCTION: getFilePath * USE: Returns the path from a given file path * @param path: The path of the file * @return: The path from the given file path */ std::string getFilePath(const std::string& path) { auto pathEnd = path.find_last_of("/\\"); auto pathName = pathEnd == std::string::npos ? path : path.substr(0, pathEnd); return pathName; } /** * FUNCTION: getFileName * USE: Returns the file name from a given file path * @param path: The path of the file * @return: The file name from the given file path */ std::string getFileName(const std::string& path) { auto fileNameStart = path.find_last_of("/\\"); auto fileName = fileNameStart == std::string::npos ? path : path.substr(fileNameStart + 1); return fileName; } /** * FUNCTION: getFileExtension * USE: Returns the file extension from a given file path * @param path: The path of the file * @return: The file extension from the given file path */ std::string getFileExtension(const std::string& path) { auto fileName = getFileName(path); auto extStart = fileName.find_last_of('.'); auto ext = extStart == std::string::npos ? "" : fileName.substr(extStart + 1); std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char c) { return static_cast<unsigned char>(std::tolower(c)); }); return ext; } }// http://programmingnotes.org/ |
5. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 5, 2020 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ #include <iostream> #include <string> #include <exception> #include "Utils.h" void display(const std::string& message); int main() { try { // Declare path std::string path = "C:\\Users\\Name\\Desktop\\20171216_155433.jpg"; // Get the file path auto filePath = Utils::getFilePath(path); display("Path: " + path + ", File Path: " + filePath); // Get the filename auto fileName = Utils::getFileName(path); display("Path: " + path + ", File Name: " + fileName); // Get the file extension auto extension = Utils::getFileExtension(path); display("Path: " + path + ", File Extension: " + extension); } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Create Multiple Tasks With Maximum Concurrency Using VB.NET

The following is a module with functions which demonstrates how to create multiple tasks with maximum concurrency using VB.NET.
The examples demonstrated on this page uses System.Threading.Tasks.Task to start and run tasks. They also use System.Threading.SemaphoreSlim to limit the number of tasks that can run concurrently.
The examples on this page demonstrates how to start and run multiple tasks with a maximum concurrency. It also demonstrates how to start and run multiple tasks with a return value.
1. Task – Maximum Concurrency
The example below demonstrates how to start and run multiple tasks with a maximum concurrency. For example purposes, the tasks do not return a value.
The functions shown in the example below are called asynchronously, but they can also be called synchronously.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
' Task - Maximum Concurrency Dim concurrentTasks = 5 Dim semaphore = New System.Threading.SemaphoreSlim(concurrentTasks, concurrentTasks) Dim tasks = New List(Of System.Threading.Tasks.Task) For count = 1 To 20 Dim taskNumber = count ' Blocks execution until another task can be started. ' This function also accepts a timeout in milliseconds Await semaphore.WaitAsync() ' Start a task Dim task = System.Threading.Tasks.Task.Run(Async Function() ' Execute long running code Try Debug.Print($"Task #{taskNumber} starting...") Await System.Threading.Tasks.Task.Delay(5000) Debug.Print($" - Task #{taskNumber} completed!") Catch ex As Exception Throw Finally ' Signal that the task is completed ' so another task can start semaphore.Release() End Try End Function) tasks.Add(task) Next Debug.Print($"Waiting for tasks to complete") ' Wait for all tasks to complete Await System.Threading.Tasks.Task.WhenAll(tasks.ToArray) Debug.Print($"All tasks completed!") ' example output: ' Task #1 starting... ' Task #2 starting... ' Task #3 starting... ' Task #4 starting... ' Task #5 starting... ' - Task #1 completed! ' - Task #2 completed! ' Task #6 starting... ' Task #7 starting... ' - Task #4 completed! ' - Task #3 completed! ' - Task #5 completed! ' Task #8 starting... ' Task #9 starting... ' Task #10 starting... ' - Task #7 completed! ' - Task #6 completed! ' Task #11 starting... ' Task #12 starting... ' - Task #9 completed! ' - Task #10 completed! ' Task #13 starting... ' Task #14 starting... ' - Task #8 completed! ' Task #15 starting... ' - Task #12 completed! ' - Task #11 completed! ' Task #16 starting... ' Task #17 starting... ' - Task #14 completed! ' - Task #13 completed! ' - Task #15 completed! ' Task #19 starting... ' Waiting for tasks to complete ' Task #18 starting... ' Task #20 starting... ' - Task #17 completed! ' - Task #16 completed! ' - Task #19 completed! ' - Task #20 completed! ' - Task #18 completed! ' All tasks completed! |
2. Task – Maximum Concurrency – Return Value
The example below demonstrates how to start and run multiple tasks with a maximum concurrency. In this example, a value is returned and retrieved from the tasks
The functions shown in the example below are called asynchronously, but they can also be called synchronously.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
' Task - Maximum Concurrency - Return Value Public Class Part Public Property PartName As String Public Property PartId As Integer End Class Dim concurrentTasks = 5 Dim semaphore = New System.Threading.SemaphoreSlim(concurrentTasks, concurrentTasks) Dim tasks = New List(Of System.Threading.Tasks.Task(Of Part)) For count = 1 To 20 Dim taskNumber = count ' Blocks execution until another task can be started. ' This function also accepts a timeout in milliseconds Await semaphore.WaitAsync() ' Start a task Dim task = System.Threading.Tasks.Task.Run(Async Function() ' Execute long running code Try Debug.Print($"Task #{taskNumber} starting...") Await System.Threading.Tasks.Task.Delay(5000) Debug.Print($" - Task #{taskNumber} completed!") ' Return result Return New Part With { .PartId = taskNumber, .PartName = $"Part #{taskNumber}" } Catch ex As Exception Throw Finally ' Signal that the task is completed ' so another task can start semaphore.Release() End Try End Function) tasks.Add(task) Next Debug.Print($"Waiting for tasks to complete") ' Wait for all tasks to complete Await System.Threading.Tasks.Task.WhenAll(tasks.ToArray) Debug.Print($"All tasks completed!") Debug.Print("") ' Get the results For Each task In tasks Dim part = task.Result Debug.Print($"Id: {part.PartId}, Name: {part.PartName}") Next ' example output: ' Task #1 starting... ' Task #2 starting... ' Task #3 starting... ' Task #4 starting... ' Task #5 starting... ' - Task #3 completed! ' - Task #2 completed! ' - Task #5 completed! ' - Task #1 completed! ' Task #8 starting... ' Task #7 starting... ' Task #6 starting... ' - Task #4 completed! ' Task #9 starting... ' Task #10 starting... ' - Task #8 completed! ' Task #11 starting... ' - Task #7 completed! ' Task #12 starting... ' - Task #6 completed! ' Task #13 starting... ' - Task #10 completed! ' - Task #9 completed! ' Task #14 starting... ' Task #15 starting... ' - Task #11 completed! ' Task #16 starting... ' - Task #12 completed! ' Task #17 starting... ' - Task #13 completed! ' Task #18 starting... ' - Task #15 completed! ' - Task #14 completed! ' Task #19 starting... ' Waiting for tasks to complete ' Task #20 starting... ' - Task #16 completed! ' - Task #17 completed! ' - Task #18 completed! ' - Task #19 completed! ' - Task #20 completed! ' All tasks completed! ' ' Id: 1, Name: Part #1 ' Id: 2, Name: Part #2 ' Id: 3, Name: Part #3 ' Id: 4, Name: Part #4 ' Id: 5, Name: Part #5 ' Id: 6, Name: Part #6 ' Id: 7, Name: Part #7 ' Id: 8, Name: Part #8 ' Id: 9, Name: Part #9 ' Id: 10, Name: Part #10 ' Id: 11, Name: Part #11 ' Id: 12, Name: Part #12 ' Id: 13, Name: Part #13 ' Id: 14, Name: Part #14 ' Id: 15, Name: Part #15 ' Id: 16, Name: Part #16 ' Id: 17, Name: Part #17 ' Id: 18, Name: Part #18 ' Id: 19, Name: Part #19 ' Id: 20, Name: Part #20 |
3. More Examples
Below is a full example of the process demonstrated on this page!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Dec 4, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates creating a task pool ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Public Class Part Public Property PartName As String Public Property PartId As Integer End Class Sub Main(args As String()) Try 'TaskSub.Wait() TaskFunction.Wait() Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Async Function TaskFunction() As Task(Of List(Of Part)) Dim concurrentTasks = 5 Dim semaphore = New System.Threading.SemaphoreSlim(concurrentTasks, concurrentTasks) Dim tasks = New List(Of System.Threading.Tasks.Task(Of Part)) For count = 1 To 20 Dim taskNumber = count ' Blocks execution until another task can be started. ' This function also accepts a timeout in milliseconds Await semaphore.WaitAsync() ' Start a task Dim task = System.Threading.Tasks.Task.Run(Async Function() ' Execute long running code Try Display($"Task #{taskNumber} starting...") Await System.Threading.Tasks.Task.Delay(5000) Display($" - Task #{taskNumber} completed!") Return New Part With { .PartId = taskNumber, .PartName = $"Part #{taskNumber}" } Catch ex As Exception Throw Finally ' Signal that the task is completed ' so another task can start semaphore.Release() End Try End Function) tasks.Add(task) Next Display($"Waiting for tasks to complete") ' Wait for all tasks to complete Await System.Threading.Tasks.Task.WhenAll(tasks.ToArray) Display($"All tasks completed!") Display("") ' Get the results For Each task In tasks Dim part = task.Result Display($"Id: {part.PartId}, Name: {part.PartName}") Next Return tasks.Select(Function(task) task.Result).ToList End Function Public Async Function TaskSub() As Task Dim concurrentTasks = 5 Dim semaphore = New System.Threading.SemaphoreSlim(concurrentTasks, concurrentTasks) Dim tasks = New List(Of System.Threading.Tasks.Task) For count = 1 To 20 Dim taskNumber = count ' Blocks execution until another task can be started. ' This function also accepts a timeout in milliseconds Await semaphore.WaitAsync() ' Start a task Dim task = System.Threading.Tasks.Task.Run(Async Function() ' Execute long running code Try Display($"Task #{taskNumber} starting...") Await System.Threading.Tasks.Task.Delay(5000) Display($" - Task #{taskNumber} completed!") Catch ex As Exception Throw Finally ' Signal that the task is completed ' so another task can start semaphore.Release() End Try End Function) tasks.Add(task) Next Display($"Waiting for tasks to complete") ' Wait for all tasks to complete Await System.Threading.Tasks.Task.WhenAll(tasks.ToArray) Display($"All tasks completed!") End Function Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Convert Bytes To Kilobytes, Megabytes, Gigabytes, Terabytes Using VB.NET

The following is a module with functions which demonstrates how to convert bytes to decimal formats like kilobytes, megabytes, gigabytes, terabytes, petabytes, exabytes, zettabytes, and yottabytes, as well as binary formats like kibibytes, mebibytes, gibibytes, tebibytes, pebibytes, exbibytes, zebibytes, and yobibytes using VB.NET.
The function demonstrated on this page follows the IEC standard, which means:
• 1 kilobyte = 1000 bytes (Decimal)
• 1 kibibyte = 1024 bytes (Binary)
This function allows you to convert bytes to a measurement unit, a measurement unit to bytes, and allows to convert from one measurement unit to another measurement unit.
1. Convert Bytes To Measurement Unit
The example below demonstrates the use of ‘Utils.Bytes.FromTo‘ to convert bytes to a measurement unit.
The optional function parameter allows you to specify the decimal places.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
' Convert Bytes To Measurement Unit ' Declare values to convert Dim values = {2287879, 536870912, 1073741824} ' Convert values For Each value In values ' Convert bytes to megabyte Dim mb = Utils.Bytes.FromTo(Utils.Bytes.Unit.Byte, value, Utils.Bytes.Unit.Megabyte) ' Convert bytes to mebibyte Dim mib = Utils.Bytes.FromTo(Utils.Bytes.Unit.Byte, value, Utils.Bytes.Unit.Mebibyte) ' Display the converted values Debug.Print($"Bytes: {value}, Megabyte: {mb}, Mebibyte: {mib}") Next ' expected output: ' Bytes: 2287879, Megabyte: 2.287879, Mebibyte: 2.18189144134521484375 ' Bytes: 536870912, Megabyte: 536.870912, Mebibyte: 512 ' Bytes: 1073741824, Megabyte: 1073.741824, Mebibyte: 1024 |
2. Convert Measurement Unit To Bytes
The example below demonstrates the use of ‘Utils.Bytes.FromTo‘ to convert a measurement unit to bytes.
The optional function parameter allows you to specify the decimal places.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
' Convert Measurement Unit To Bytes ' Declare values to convert Dim values = {1, 0.5D, 10.75D} ' Convert values For Each value In values ' Convert gibibyte to byte Dim bytes = Utils.Bytes.FromTo(Utils.Bytes.Unit.Gibibyte, value, Utils.Bytes.Unit.Byte) ' Display the converted values Debug.Print($"Gibibyte: {value}, Bytes: {bytes}") Next ' expected output: ' Gibibyte: 1, Bytes: 1073741824 ' Gibibyte: 0.5, Bytes: 536870912.0 ' Gibibyte: 10.75, Bytes: 11542724608.00 |
3. Convert Measurement Unit To Measurement Unit
The example below demonstrates the use of ‘Utils.Bytes.FromTo‘ to convert a measurement unit to another measurement unit.
The optional function parameter allows you to specify the decimal places.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
' Convert Measurement Unit To Measurement Unit ' Declare values to convert Dim values = {1991, 1987, 28.31D, 19.22D} ' Convert values For Each value In values ' Convert value from one unit to another Dim size = Utils.Bytes.FromTo(Utils.Bytes.Unit.Gigabyte, value, Utils.Bytes.Unit.Terabyte) ' Display the converted values Debug.Print($"Gigabyte: {value}, Terabyte: {size}") Next ' expected output: ' Gigabyte: 1991, Terabyte: 1.991 ' Gigabyte: 1987, Terabyte: 1.987 ' Gigabyte: 28.31, Terabyte: 0.02831 ' Gigabyte: 19.22, Terabyte: 0.01922 |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Dec 3, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Namespace Bytes Public Module modBytes Public Enum Unit [Byte] ' Decimal Kilobyte Megabyte Gigabyte Terabyte Petabyte Exabyte Zettabyte Yottabyte ' Binary Kibibyte Mebibyte Gibibyte Tebibyte Pebibyte Exbibyte Zebibyte Yobibyte End Enum ''' <summary> ''' Converts a measurement 'Unit' to another measurement 'Unit' ''' </summary> ''' <param name="unitFrom">The measurement unit converting from</param> ''' <param name="sizeFrom">The size of the 'from' measurement unit</param> ''' <param name="unitTo">The measurement unit to convert to</param> ''' <param name="decimalPlaces">The decimal places to round to</param> ''' <returns>The value converted to the specified measurement unit</returns> Public Function FromTo(unitFrom As Unit, sizeFrom As Decimal, unitTo As Unit _ , Optional decimalPlaces As Integer? = Nothing) As Decimal Dim result = sizeFrom If unitFrom <> unitTo Then If unitFrom = Unit.Byte Then result = ConvertTo(unitTo, sizeFrom, decimalPlaces) ElseIf unitTo = Unit.Byte Then result = ConvertFrom(unitFrom, sizeFrom, decimalPlaces) Else result = ConvertTo(unitTo, ConvertFrom(unitFrom, sizeFrom), decimalPlaces) End If End If Return result End Function Private Enum Conversion From [To] End Enum ' Converts bytes to a measurement unit Private Function ConvertTo(unit As Unit, bytes As Decimal _ , Optional decimalPlaces As Integer? = Nothing) As Decimal Return Convert(Conversion.To, bytes, unit, decimalPlaces) End Function ' Converts a measurement unit to bytes Private Function ConvertFrom(unit As Unit, bytes As Decimal _ , Optional decimalPlaces As Integer? = Nothing) As Decimal Return Convert(Conversion.From, bytes, unit, decimalPlaces) End Function Private Function Convert(operation As Conversion, bytes As Decimal, unit As Unit _ , decimalPlaces As Integer?) As Decimal ' Get the unit type definition Dim definition = GetDefinition(unit) If definition Is Nothing Then Throw New ArgumentException($"Unknown unit type: {unit}", NameOf(unit)) End If ' Get the unit value Dim value = definition.Value ' Calculate the result Dim result = If(operation = Conversion.To, bytes / value, bytes * value) If decimalPlaces.HasValue Then result = Math.Round(result, decimalPlaces.Value, MidpointRounding.AwayFromZero) End If Return result End Function Public Enum Prefix [Decimal] Binary End Enum Public Class Definition Public Property Prefix As Prefix Public Property OrderOfMagnitude As Integer Public ReadOnly Property Multiple As Decimal Get Return If(Prefix = Prefix.Decimal, 1000, 1024) End Get End Property Public ReadOnly Property Value As Decimal Get Return CDec(Math.Pow(Multiple, OrderOfMagnitude)) End Get End Property End Class Public Function GetDefinition(unit As Unit) As Definition Dim definitions = GetDefinitions() Return If(definitions.ContainsKey(unit), definitions(unit), Nothing) End Function Public Function GetDefinitions() As Dictionary(Of Unit, Definition) ' Create and add definitions Static definitions As Dictionary(Of Unit, Definition) If definitions Is Nothing Then definitions = New Dictionary(Of Unit, Definition) ' Place units in order of magnitude ' Decimal units Dim decimals = { Unit.Kilobyte, Unit.Megabyte, Unit.Gigabyte, Unit.Terabyte _ , Unit.Petabyte, Unit.Exabyte, Unit.Zettabyte, Unit.Yottabyte } ' Binary units Dim binary = { Unit.Kibibyte, Unit.Mebibyte, Unit.Gibibyte, Unit.Tebibyte _ , Unit.Pebibyte, Unit.Exbibyte, Unit.Zebibyte, Unit.Yobibyte } AddDefinitions(definitions, Prefix.Decimal, decimals) AddDefinitions(definitions, Prefix.Binary, binary) End If Return definitions End Function Private Sub AddDefinitions(definitions As Dictionary(Of Unit, Definition) _ , prefix As Prefix, units As IEnumerable(Of Unit)) For index = 0 To units.Count - 1 Dim unit = units(index) If Not definitions.ContainsKey(unit) Then definitions.Add(unit, New Definition With { .Prefix = prefix, .OrderOfMagnitude = index + 1 }) End If Next End Sub End Module End Namespace End Namespace ' http://programmingnotes.org/ |
5. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Dec 3, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Sub Main(args As String()) Try ' Declare values to convert Dim values = {2287879, 536870912, 1073741824} ' Convert values For Each value In values ' Convert bytes to megabyte Dim mb = Utils.Bytes.FromTo(Utils.Bytes.Unit.Byte, value, Utils.Bytes.Unit.Megabyte) ' Convert bytes to mebibyte Dim mib = Utils.Bytes.FromTo(Utils.Bytes.Unit.Byte, value, Utils.Bytes.Unit.Mebibyte) ' Display the converted values Display($"Bytes: {value}, Megabyte: {mb}, Mebibyte: {mib}") Next Display("") ' Declare values to convert Dim values2 = {1, 0.5D, 10.75D} ' Convert values For Each value In values2 ' Convert gibibyte to byte Dim bytes = Utils.Bytes.FromTo(Utils.Bytes.Unit.Gibibyte, value, Utils.Bytes.Unit.Byte) ' Display the converted values Display($"Gibibyte: {value}, Bytes: {bytes}") Next Display("") ' Declare values to convert Dim values3 = {1991, 1987, 28.31D, 19.22D} ' Convert values For Each value In values3 ' Convert value from one unit to another Dim size = Utils.Bytes.FromTo(Utils.Bytes.Unit.Gigabyte, value, Utils.Bytes.Unit.Terabyte) ' Display the converted values Display($"Gigabyte: {value}, Terabyte: {size}") Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Parse A Delimited CSV File Using VB.NET

The following is a module with functions which demonstrates how to parse a delimited CSV file using VB.NET.
The function demonstrated on this page uses FileIO.TextFieldParser to parse values in a CSV file.
This function parses a CSV file and returns its results as a List. Each List index represents a line in the CSV file, with each item in the list representing a record contained on that line.
1. Parse CSV File
The example below demonstrates the use of ‘Utils.ParseCsv‘ to parse a CSV file and return its results as a List.
The optional function parameter allows you to specify the delimiters. Default delimiter is a comma (,).
Sample CSV used in this example is the following:
1 2 3 4 5 6 |
Kenneth,Perkins,120 jefferson st.,Riverside, NJ, 08075 Jack,McGinnis,220 hobo Av.,Phila, PA,09119 "Jennifer ""Da Man""",Repici,120 Jefferson St.,Riverside, NJ,08075 Stephen,Tyler,"7452 Terrace ""At the Plaza"" road",SomeTown,SD, 91234 ,Blankman,,SomeTown, SD, 00298 "Joan ""the bone"", Anne",Jet,"9th, at Terrace plc",Desert City,CO,00123 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
' Parse CSV File ' Read file into byte array Dim fileBytes As Byte() ' Parse the contents of the file into a list Dim fileContents = Utils.ParseCsv(fileBytes) ' Display the contents of the file For lineIndex = 0 To fileContents.Count - 1 Dim line = fileContents(lineIndex) Debug.Print($"Line #{lineIndex + 1}") For Each item In line Debug.Print($" Item: {item}") Next Next ' expected output: ' Line #1 ' Item: Kenneth ' Item: Perkins ' Item: 120 jefferson st. ' Item: Riverside ' Item: NJ ' Item: 08075 ' Line #2 ' Item: Jack ' Item: McGinnis ' Item: 220 hobo Av. ' Item: Phila ' Item: PA ' Item: 09119 ' Line #3 ' Item: Jennifer "Da Man" ' Item: Repici ' Item: 120 Jefferson St. ' Item: Riverside ' Item: NJ ' Item: 08075 ' Line #4 ' Item: Stephen ' Item: Tyler ' Item: 7452 Terrace "At the Plaza" road ' Item: SomeTown ' Item: SD ' Item: 91234 ' Line #5 ' Item: ' Item: Blankman ' Item: ' Item: SomeTown ' Item: SD ' Item: 00298 ' Line #6 ' Item: Joan "the bone", Anne ' Item: Jet ' Item: 9th, at Terrace plc ' Item: Desert City ' Item: CO ' Item: 00123 |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Dec 2, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Parses a Csv file and returns its results as a List. ''' Each List index represents a line in the Csv file, with each ''' item in the list representing a record contained on that line. ''' </summary> ''' <param name="fileBytes">The Csv file as a byte array</param> ''' <param name="delimiters">The Csv data delimiter</param> ''' <returns>The file contents as a List</returns> Public Function ParseCsv(fileBytes As Byte() _ , Optional delimiters As String = ",") As List(Of List(Of String)) Dim results = New List(Of List(Of String)) Using stream = New System.IO.MemoryStream(fileBytes) Using parser = New Microsoft.VisualBasic.FileIO.TextFieldParser(stream) parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited parser.Delimiters = delimiters.Select(Function(letter) letter.ToString).ToArray parser.HasFieldsEnclosedInQuotes = True ' Parse each line in the file While Not parser.EndOfData Dim currentLine = parser.ReadFields results.Add(currentLine.ToList) End While End Using End Using Return results End Function End Module End Namespace ' http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Dec 2, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Sub Main(args As String()) Try ' Read file into byte array Dim fileBytes As Byte() ' Parse the contents of the file into a list Dim fileContents = Utils.ParseCsv(fileBytes) ' Display the contents of the file For lineIndex = 0 To fileContents.Count - 1 Dim line = fileContents(lineIndex) Display($"Line #{lineIndex + 1}") For Each item In line Display($" Item: {item}") Next Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.