Found 2628 Articles for Csharp

How to get all the directories and sub directories inside a path in C#?

Nizamuddin Siddiqui
Updated on 25-Nov-2020 11:51:51

21K+ Views

To get the directories C# provides a method Directory.GetDirectories. The Directory.GetDirectories method returns the names of the subdirectories (including their paths) that match the specified search pattern in the specified directory, and optionally searches subdirectories.In the below example * is matches Zero or more characters in that position. SearchOption TopDirectoryOnly .Gets only the top directories and SearchOption AllDirectories .Gets all the top directories and sub directories.Note: The rootPath will be your systems rootPath so create a testfolder and use the rootPath accoridingly.Example 1static void Main (string[] args) {    string rootPath = @"C:\Users\Koushik\Desktop\TestFolder";    string[] dirs = Directory.GetDirectories(rootPath, "*", SearchOption.TopDirectoryOnly); ... Read More

How to convert IEnumerable to List and List back to IEnumerable in C#?

Nizamuddin Siddiqui
Updated on 25-Nov-2020 11:49:42

7K+ Views

IEnumerable is an interface defining a single method GetEnumerator() that returns an IEnumerator interface. It is the base interface for all non-generic collections that can be enumerated.This works for read-only access to a collection that implements that IEnumerable can be used with a foreach statement.List class represents the list of objects which can be accessed by index. It comes under the System.Collection.Generic namespace.List class can be used to create a collection of different types like integers, strings etc. List class also provides the methods to search, sort, and manipulate lists.Example 1static void Main(string[] args) {    List list = new ... Read More

How to check Minlength and Maxlength validation of a property in C# using Fluent Validation?

Nizamuddin Siddiqui
Updated on 25-Nov-2020 11:46:46

2K+ Views

MaxLength ValidatorEnsures that the length of a particular string property is no longer than the specified value.Only valid on string propertiesString format args:{PropertyName} = The name of the property being validated{MaxLength} = Maximum length{TotalLength} = Number of characters entered{PropertyValue} = The current value of the propertyMinLength ValidatorEnsures that the length of a particular string property is longer than the specified value.Only valid on string properties{PropertyName} = The name of the property being validated{MinLength} = Minimum length{TotalLength} = Number of characters entered{PropertyValue} = The current value of the propertyExamplestatic void Main(string[] args){    List errors = new List();    PersonModel ... Read More

How to valid DateofBirth using fluent Validation in C# if it exceeds current year?

Nizamuddin Siddiqui
Updated on 25-Nov-2020 11:44:03

3K+ Views

To specify a validation rule for a particular property, call the RuleFor method, passing a lambda expression that indicates the property that you wish to validateRuleFor(p => p.DateOfBirth)To run the validator, instantiate the validator object and call the Validate method, passing in the object to validate.ValidationResult results = validator.Validate(person);The Validate method returns a ValidationResult object. This contains two propertiesIsValid - a boolean that says whether the validation suceeded.Errors - a collection of ValidationFailure objects containing details about any validation failuresExample 1static void Main(string[] args) {    List errors = new List();    PersonModel person = new PersonModel();    person.FirstName ... Read More

What is use of fluent Validation in C# and how to use in C#?

Nizamuddin Siddiqui
Updated on 25-Nov-2020 11:41:41

2K+ Views

FluentValidation is a .NET library for building strongly-typed validation rules. It Uses a fluent interface and lambda expressions for building validation rules. It helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logicTo make use of fluent validation we have to install the below packageExample 1static class Program {    static void Main (string[] args) {       List errors = new List();       PersonModel person = new PersonModel();       person.FirstName = "";       person.LastName = "S";   ... Read More

How to copy files into a directory in C#?

Nizamuddin Siddiqui
Updated on 25-Nov-2020 11:37:24

3K+ Views

To Copy a file, C# provides a method File. CopyFile. Copy has 2 overloadsCopy(String, String) -Copies an existing file to a new file. Overwriting a file of the same name is not allowed.Copy(String, String, Boolean) Copies an existing file to a new file. Overwriting a file of the same name is allowed.Directory.GetFiles returns the names of all the files (including their paths) that match the specified search pattern, and optionally searches subdirectories.Examplestatic void Main (string[] args) {    string rootPath = @"C:\Users\Koushik\Desktop\TestFolder\TestFolderMain1";    var searchSourceFolder = Directory.GetFiles(rootPath, "*.*", SearchOption.TopDirectoryOnly);    Console.WriteLine("-------------Source Folder-------------");    foreach (string file in searchSourceFolder){   ... Read More

What are the different ways to implement dependency injection and their advantages in C#?

Nizamuddin Siddiqui
Updated on 25-Nov-2020 11:33:47

2K+ Views

The process of injecting (converting) coupled (dependent) objects into decoupled (independent) objects is called Dependency Injection.Types of Dependency InjectionThere are four types of DI:1.Constructor Injection2.Setter Injection3.Interface-based injection4.Service Locator InjectionConstructor InjectionConstructor is used to interface parameter that exposed through the parameterized contractor.It injects the dependencies through a contractor method as object creation other classes.Setter InjectionGetter and Setter Injection injects the dependency by using default public properties procedure such as Gettter(get(){}) and Setter(set(){}). TInterface InjectionInterface Injection is similar to Getter and Setter DI, the Getter and Setter DI uses default getter and setter but Interface Injection uses support interface a kind of ... Read More

How to convert XML to Json and Json back to XML using Newtonsoft.json?

Nizamuddin Siddiqui
Updated on 25-Nov-2020 11:32:31

2K+ Views

Json.NET supports converting JSON to XML and vice versa using the XmlNodeConverter.Elements, attributes, text, comments, character data, processing instructions, namespaces, and the XML declaration are all preserved when converting between the twoSerializeXmlNodeThe JsonConvert has two helper methods for converting between JSON and XML. The first is SerializeXmlNode(). This method takes an XmlNode and serializes it to JSON text.DeserializeXmlNodeThe second helper method on JsonConvert is DeserializeXmlNode(). This method takes JSON text and deserializes it into an XmlNode.Example 1static void Main(string[] args) {    string xml = @"Alanhttp://www.google1.com Admin1";    XmlDocument doc = new XmlDocument();    doc.LoadXml(xml);    string json = JsonConvert.SerializeXmlNode(doc); ... Read More

How to resize an Image C#?

Nizamuddin Siddiqui
Updated on 07-Nov-2020 12:14:52

477 Views

A bitmap consists of the pixel data for a graphics image and its attributes. There are many standard formats for saving a bitmap to a file. GDI+ supports the following file formats: BMP, GIF, EXIF, JPG, PNG and TIFF. You can create images from files, streams, and other sources by using one of the Bitmap constructors and save them to a stream or to the file system with the Save method.In the below code CompressAndSaveImageAsync Method Compresses the images and saves in the path Mentioned.The new image name will be a combination of desktop userId and dateTimeExampleprivate async Task CompressAndSaveImageAsync(Bitmap ... Read More

How can I limit Parallel.ForEach in C#?

Nizamuddin Siddiqui
Updated on 07-Nov-2020 12:12:44

1K+ Views

Parallel ForeachParallel.ForEach loop in C# runs upon multiple threads and processing takes place in a parallel way. Parallel.ForEach loop is not a basic feature of C# and it is available from C# 4.0 and above To use Parallel.ForEach loop we need to import System.Threading.Tasks namespace in using directive.ForeachForeach loop in C# runs upon a single thread and processing takes place sequentially one by one. Foreach loop is a basic feature of C# and it is available from C# 1.0. Its execution is slower than the Parallel.Foreach in most of the cases.Example 1static void Main(string[] args){    List alphabets = new ... Read More

Advertisements