Daily Archives: May 13, 2021
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 System.IO.FileInfo, which contains information about the files in the given directory.
1. Get Files In Directory
The example below demonstrates the use of ‘Utils.Methods.GetFilesInDirectory‘ to get a list of files at a given path directory.
The optional function parameter lets you specify the search option. This lets you specify whether to limit the search to just the current directory, or 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 directory path var directory = $@"C:\Users\Name\Desktop"; // Get files at the specified directory var files = Utils.Methods.GetFilesInDirectory(directory); // Display info about the files foreach (var file in files) { Console.WriteLine($"File: {file.FullName} - Last Modified: {file.LastWriteTime}"); } // example output: /* File: C:\Users\Name\Desktop\text.txt - Last Modified: 10/7/2020 12:47:56 PM File: C:\Users\Name\Desktop\image.png - Last Modified: 9/4/2020 8:36:25 PM File: C:\Users\Name\Desktop\document.docx - Last Modified: 3/7/2018 9:26:19 PM */ |
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: May 13, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Linq; using System.Collections.Generic; namespace Utils { public static class Methods { /// <summary> /// Returns a list of <see cref="System.IO.FileInfo"/> of the files /// in the given directory /// </summary> /// <param name="directory">The relative or absolute path to the directory to search</param> /// <param name="searchOption">The file search option</param> /// <returns>A list of <see cref="System.IO.FileInfo"/> in the given directory</returns> public static List<System.IO.FileInfo> GetFilesInDirectory(string directory , System.IO.SearchOption searchOption = System.IO.SearchOption.TopDirectoryOnly) { return System.IO.Directory.GetFiles(directory, "*", searchOption) .Select(fileName => new System.IO.FileInfo(fileName)).ToList(); } } }// 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: May 13, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using System.Collections.Generic; public class Program { static void Main(string[] args) { try { // Declare directory path var directory = $@"C:\path\to\directory"; // Get files at the specified directory var files = Utils.Methods.GetFilesInDirectory(directory); // Display info about the files foreach (var file in files) { Display($"File: {file.FullName} - Last Modified: {file.LastWriteTime}"); } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// 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 Computer & User Client IP Address Using C#
The following is a module with functions which demonstrates how to get the computers and user client request IPv4 IP address using C#.
The function demonstrated on this page returns the IPv4 address of the calling user. When under a web environment, it returns the clients System.Web.HttpContext.Current.Request IP address, otherwise it returns the IP address of the local machine (i.e: server) if there is no request.
The following function uses System.Web to determine the IP address of the client.
Note: To use the function in this module, make sure you have a reference to ‘System.Web‘ in your project.
One way to do this is, in your Solution Explorer (where all the files are shown with your project), right click the ‘References‘ folder, click ‘Add Reference‘, then type ‘System.Web‘ in the search box, and add the reference titled System.Web in the results Tab.
1. Get IP Address
The example below demonstrates the use of ‘Utils.Methods.GetIPv4Address‘ to get the IPv4 address of the calling user.
1 2 3 4 5 6 7 8 9 10 11 |
// Get IP Address // Get IP address of the current user var ipAddress = Utils.Methods.GetIPv4Address(); Console.WriteLine($"IP Address: {ipAddress}"); // example output: /* IP Address: 192.168.0.5 */ |
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 13, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Linq; namespace Utils { public static class Methods { /// <summary> /// Returns the IPv4 address of the calling user. When under a web /// environment, returns the <see cref="System.Web.HttpRequest"/> /// IP address, otherwise returns the IP address of the local machine /// </summary> /// <returns>The IPv4 address of the calling user</returns> public static string GetIPv4Address() { var ipAddress = string.Empty; // Get client ip address if (System.Web.HttpContext.Current != null && System.Web.HttpContext.Current.Request != null) { // Get client ip address using ServerVariables var request = System.Web.HttpContext.Current.Request; ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!string.IsNullOrEmpty(ipAddress)) { var addresses = ipAddress.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (addresses.Length > 0) { ipAddress = addresses[0]; } } if (string.IsNullOrEmpty(ipAddress)) { ipAddress = request.ServerVariables["REMOTE_ADDR"]; } // Get client ip address using UserHostAddress if (string.IsNullOrEmpty(ipAddress)) { var clientIPA = GetNetworkAddress(request.UserHostAddress); if (clientIPA != null) { ipAddress = clientIPA.ToString(); } } } // Get local machine ip address if (string.IsNullOrEmpty(ipAddress)) { var loacalIPA = GetNetworkAddress(System.Net.Dns.GetHostName()); if (loacalIPA != null) { ipAddress = loacalIPA.ToString(); } } return ipAddress; } private static System.Net.IPAddress GetNetworkAddress(string addresses) { return System.Net.Dns.GetHostAddresses(addresses) .FirstOrDefault(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork); } } }// 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 13, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; public class Program { static void Main(string[] args) { try { // Get IP address of the current user var ipAddress = Utils.Methods.GetIPv4Address(); Display($"IP Address: {ipAddress}"); } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// 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 Copy DataTable DataRow From One DataRow To Another Using C#
The following is a module with functions which demonstrates how to copy a DataTable DataRow from one DataRow to another using C#.
The function demonstrated on this page is an extension method, which copies all matching columns from the source DataRow to the destination DataRow. If no matching column exists between the two rows, the data at that column is skipped. This allows to safely copy a single row from one DataTable to other.
1. Copy DataRow
The example below demonstrates the use of ‘Utils.Collections.Extensions.CopyTo‘ to copy all matching columns from a source row to a destination row.
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 |
// Copy DataRow using Utils.Collections; // Declare the source datatable var table1 = new DataTable(); table1.Columns.Add("Name", typeof(string)); table1.Rows.Add("Kenneth"); table1.Rows.Add("Jennifer"); table1.Rows.Add("Lynn"); table1.Rows.Add("Sole"); table1.Rows.Add(System.DBNull.Value); // Declare the destination datatable var table2 = new DataTable(); table2.Columns.Add("Id", typeof(int)); table2.Columns.Add("Name", typeof(string)); for (var index = 0; index < table1.Rows.Count; ++index) { // Get the source row var rowSource = table1.Rows[index]; // Get the destination row var rowDestination = table2.NewRow(); // Do something with the destination row rowDestination["Id"] = index + 1; // Copy contents from source to destination rowSource.CopyTo(rowDestination); table2.Rows.Add(rowDestination); } // Display information from destination table foreach (DataRow row in table2.Rows) { Console.WriteLine($"Id: {row["Id"]}, Name: {row["Name"]}"); } // expected output: /* Id: 1, Name: Kenneth Id: 2, Name: Jennifer Id: 3, Name: Lynn Id: 4, Name: Sole Id: 5, Name: */ |
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: May 13, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; using System.Data; namespace Utils { namespace Collections { public static class Extensions { /// <summary> /// Copies all matching columns from the source row to the destination row /// </summary> /// <param name="source">The DataRow source</param> /// <param name="destination">The DataRow destination</param> public static void CopyTo(this DataRow source, DataRow destination) { foreach (DataColumn col in source.Table.Columns) { if (destination.Table.Columns.Contains(col.ColumnName)) { destination[col.ColumnName] = source[col.ColumnName]; } } } } } } |
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 13, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using Utils.Collections; using System.Data; public class Program { static void Main(string[] args) { try { // Declare the source datatable var table1 = new DataTable(); table1.Columns.Add("Name", typeof(string)); table1.Rows.Add("Kenneth"); table1.Rows.Add("Jennifer"); table1.Rows.Add("Lynn"); table1.Rows.Add("Sole"); table1.Rows.Add(System.DBNull.Value); // Declare the destination datatable var table2 = new DataTable(); table2.Columns.Add("Id", typeof(int)); table2.Columns.Add("Name", typeof(string)); for (var index = 0; index < table1.Rows.Count; ++index) { // Get the source row var rowSource = table1.Rows[index]; // Get the destination row var rowDestination = table2.NewRow(); // Do something with the destination row rowDestination["Id"] = index + 1; // Copy contents from source to destination rowSource.CopyTo(rowDestination); table2.Rows.Add(rowDestination); } // Display information from destination table foreach (DataRow row in table2.Rows) { Display($"Id: {row["Id"]}, Name: {row["Name"]}"); } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// 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 Generate, Create & Read A QR Code Using C#
The following is a module with functions which demonstrates how to generate, create and read a QR code using C#.
The functions demonstrated on this page has the ability to create and encode a string to a QR code byte array, and another function to read and decode a byte array QR code to a string.
The following functions use ZXing.Net to create and read QR codes.
Note: To use the functions in this module, make sure you have the ‘ZXing.Net‘ package installed in your project.
One way to do this is, in your Solution Explorer (where all the files are shown with your project), right click the ‘References‘ folder, click ‘Manage NuGet Packages….‘, then type ‘ZXing.Net‘ in the search box, and install the package titled ZXing.Net in the results Tab.
1. Create QR Code – Encode
The example below demonstrates the use of ‘Utils.QRCode.Create‘ to create a QR code byte array from string data.
The optional function parameters allows you to specify the QR code height, width and margin.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Create QR Code - Encode // Data to encode var data = "https://www.programmingnotes.org/"; // Encode data to a QR code byte array var qrBytes = Utils.QRCode.Create(data); // Display bytes length Console.WriteLine($"Length: {qrBytes.Length}"); // expected output: /* Length: 1959 */ |
2. Read QR Code – Decode
The example below demonstrates the use of ‘Utils.QRCode.Read‘ to read a QR code byte array and decode its contents to a string.
1 2 3 4 5 6 7 8 9 |
// Read QR Code - Decode // Read QR as byte array byte[] qrBytes; // Decode QR code to a string var data = Utils.QRCode.Read(qrBytes); // ... Do something with the result string |
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 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 13, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class QRCode { /// <summary> /// Converts a string and encodes it to a QR code byte array /// </summary> /// <param name="data">The data to encode</param> /// <param name="height">The height of the QR code</param> /// <param name="width">The width of the QR code</param> /// <param name="margin">The margin around the QR code</param> /// <returns>The byte array of the data encoded into a QR code</returns> public static byte[] Create(string data, int height = 100 , int width = 100, int margin = 0) { byte[] bytes = null; var barcodeWriter = new ZXing.BarcodeWriter() { Format = ZXing.BarcodeFormat.QR_CODE, Options = new ZXing.QrCode.QrCodeEncodingOptions() { Height = height, Width = width, Margin = margin } }; using (var image = barcodeWriter.Write(data)) { using (var stream = new System.IO.MemoryStream()) { image.Save(stream, System.Drawing.Imaging.ImageFormat.Png); bytes = stream.ToArray(); } } return bytes; } /// <summary> /// Converts a QR code and decodes it to its string data /// </summary> /// <param name="bytes">The QR code byte array</param> /// <returns>The string data decoded from the QR code</returns> public static string Read(byte[] bytes) { var result = string.Empty; using (var stream = new System.IO.MemoryStream(bytes)) { using (var image = System.Drawing.Image.FromStream(stream)) { var barcodeReader = new ZXing.BarcodeReader() { AutoRotate = true, TryInverted = true, Options = new ZXing.Common.DecodingOptions() { TryHarder = true, PossibleFormats = new ZXing.BarcodeFormat[] { ZXing.BarcodeFormat.QR_CODE } } }; var decoded = barcodeReader.Decode((System.Drawing.Bitmap)image); if (decoded != null) { result = decoded.Text; } } } 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 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 13, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; public class Program { static void Main(string[] args) { try { // Data to encode var data = "https://www.programmingnotes.org/"; // Encode data to a QR code byte array var bytes = Utils.QRCode.Create(data); Display($"Length: {bytes.Length}"); // Decode QR code to a string var result = Utils.QRCode.Read(bytes); Display($"Result: {result}"); } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// 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.