· 7 years ago · Dec 04, 2018, 06:52 PM
1In this article we’ll learn all about C# with some of the best articles on C# Corner which I find most helpful for every C# Developer.
2
3Here is the list of the 10 most important things in C#.
4
5Advantages of C#
6Future of C#
7Abstraction in C#
8Encapsulation in C#
9Inheritance in C#
10Polymorphism in C#
11Delegates in C#
12Collections in C#
13Exception handling in C#
14File Handling in C#
151. Advantages of C# over Java
16
17I have found some interesting advantages of C# over Java and for that I have also won the prize from the Java team...!!. So I want to share it with all people so others can also know about it.
18
19C# being a .NET language, it supports language interoperability, i.e. C# can access code written in any .NET compliant language and can also inherit the classes written in these languages. This is not possible in Java.
20
21The code written in C#, on compilation generates an ‘.exe' or ‘.dll' file which is also called Portable Executable file. These files contain MSIL (Microsoft Intermediate Language) code. As against this, the Java code on compilation generates a ‘.class' file, which contains bytecode.
22
23The portable executable file of C# can contain any number of classes, whereas, the ‘.class' file in Java contains only one class.
24
25The methods in C# are not virtual by default. On the contrary, methods in Java are virtual by default, which degrades the performance.
26
27The classes in C# are grouped in Namespaces, whereas, classes in Java are grouped in Packages.
28
29The C# namespaces are not related to the directories. The packages in Java are directly related with the directory names.
30
31The variables of primitive data types in C# are more powerful. This is because even though they are not objects functions can be called using them. The variables of primitive data types in Java cannot call functions.
32
33C# has features like Properties and Indexers. These features are not available in the Java language.
34
35C# supports Structures, Operator Overloading and Pre-processors directives, whereas, Java has none of them.
36
37Through C# we can easily call Windows API function and access COM components which is quite difficult in Java.
38For more follow the link:
39Advantages of C# Over Java
402. Future of C#
41
42Today, C# is not only a Windows development programming language but can be used to build Web applications, Windows store apps, and mobile apps including iOS and Android. C# can also do more than that. If you’ve not already read my article, I highly recommend going and reading What C# Can Do For You.
43
44At the Build 2016 event, Microsoft made several exciting announcements and one of them was integrating Xamarin as a part of Visual Studio “15†and beyond. Now C# developers can build iOS and Android apps that can spit out native iOS and Android code.
45
46...the future of C# is very bright.
47
48In the following Channel 9 video, Microsoft’s Dustin Campbell and Mads Torgersen talk about the future of C#.
49
50Here are some of the bullet points from the video:
51
52You can write C# in any editor you want.
53
54C# is open source now
55
56C# runs on Windows, Mac, and Linux
57
58C# can be used to build Windows client apps, Windows Store apps, iOS apps, and Android aps and can also be used to build backend and middle-tier frameworks and libraries.
59
60C# (via Roslyn, the C# engine):
61
62Supports all IDEs and editors
63
64All the linters and analysis tools
65
66All the fixing and refactoring and code generation tools
67
68All the scripting and all the REPLs
69
70C# 7 comes with new features including tuples, record types, and pattern matching.
71
72C# is young and evolving.
73
74Unlike other programming languages, C# is still young and evolving. Now being open sourced, C# is getting community involvement and new features are being decided by community. The following table summarizes the improvements made in each newer version of the language.
75
76Version Year Key features introduced
771.0 Jan 2002
781.2 Oct 2003 Modern, object-oriented, type safe, automatic memory management, versioning control
792.0 Sept 2005 Generics, partial classes, anonymous types, iterators, nullable types, static classes, delegate interface
803.0 Aug 2007 Implicit types, object and collection initializers, auto-implemented properties, extension methods, query and lambda expressions, expression trees, partial methods.
814.0 April 2010 Dynamic binding, named and optional arguments, Generic covariance and Contravariance, Embedded interop types.
825.0 June 2013 Async methods, Caller info Attributes
836.0 July 2015 Roslyn (compiler-as-a-service), exception filters, Await in catch/finally block, auto property initializer, string interpolation, nameof operator, dictionary initializer
847.0 2016 Tuples, pattern matching, record types, local functions, Async streams
85For more follow the link:
86
87What Is The Future Of C#
88
893. Abstraction in C#
90
91The word abstract means a concept or an idea not associated with any specific instance. In programming we apply the same meaning of abstraction by making classes not associated with any specific instance. The abstraction is done when we need to only inherit from a certain class, but do not need to instantiate objects of that class. In such case the base class can be regarded as "Incomplete". Such classes are known as an "Abstract Base Class".
92
93Abstract Base Class
94
95There are some important points about Abstract Base Class :
96
97An Abstract Base class can not be instantiated; it means the object of that class can not be created.
98
99Class having abstract keyword and having abstract keyword with some of its methods (not all) is known as an Abstract Base Class.
100
101Class having Abstract keyword and having abstract keyword with all of its methods is known as pure Abstract Base Class.
102
103The method of abstract class that has no implementation is known as "operation". It can be defined as abstract void method ();
104
105An abstract class holds the methods but the actual implementation of those methods is made in derived class.
106Lets have a look at this code!
107abstract class animal
108{
109 public abstract void eat();
110 public void sound()
111 {
112 Console.WriteLine("dog can sound");
113 }
114}
115This is the Abstract Base Class, if I make both of its methods abstract then this class would become a pure Abstract Base Class.
116
117Now we derive a class of 'dog' from the class animal.
118abstract class animal
119{
120 public abstract void eat();
121 public void sound()
122 {
123 Console.WriteLine("dog can sound");
124 }
125}
126class dog: animal
127{
128 public override void eat()
129 {
130 Console.WriteLine("dog can eat");
131 }
132}
133Here you can see we have 2 methods in the Abstract Base Class, the method eat() has no implementation; that is why it is being declared as 'abstract' while the method sound() has its own body so it is not declared as 'abstract'.
134
135In the derived class we have the same named method but this method has its body.
136
137We are doing abstraction here so that we can access the method of derived class without any trouble.
138
139Let's have a look!
140class program
141{
142 abstract class animal
143 {
144 public abstract void eat();
145 public void sound()
146 {
147 Console.WriteLine("dog can sound");
148 }
149 }
150 class dog: animal
151 {
152 public override void eat()
153 {
154 Console.WriteLine("dog can eat");
155 }
156 }
157 static void Main(string[] args)
158 {
159 dog mydog = new dog();
160 animal thePet = mydog;
161 thePet.eat();
162 mydog.sound();
163 }
164}
165Finally we created an Object 'mydog' of class dog, but we didn't instantiate any object of Abstract Base Class 'animal'.
166
167According to "Ivor Horton" (a programmer of Java) an object can not be instantiated, but we can declare a variable of the Abstract Class type. If this statement is true then it could be possible:
168
169animal thePet;
170
171This is an object which is declared as thePet and its data type is the abstract base class 'animal'.
172
173We can use this Object to store Objects of the subclass.
174
175In the above code we declare an Object 'thePet', of the type animal (the Abstract Base Class) and simply copy the object of another object (only the reference is copied as they belong to reference type). Now we can use object 'thePet' just as object 'mydog'.
176
177The output of this code would be,
178
179dog can eat
180dog can sound
181
182For more follow the link:
183Abstraction in C#
1844. Encapsulation in C#
185
186The object oriented programming will give the impression very unnatural to a programmer with a lot of procedural programming experience. In Object Oriented programming Encapsulation is the first place. Encapsulation is the procedure of covering up of data and functions into a single unit (called class). An encapsulated object is often called an abstract data type. In this article let us see about it in a detailed manner.
187
188NEED FOR ENCAPSULATION
189
190The need of encapsulation is to protect or prevent the code (data) from accidental corruption due to the silly little errors that we are all prone to make. In Object oriented programming data is treated as a critical element in the program development and data is packed closely to the functions that operate on it and protects it from accidental modification from outside functions.
191
192Encapsulation provides a way to protect data from accidental corruption. Rather than defining the data in the form of public, we can declare those fields as private. The Private data are manipulated indirectly by two ways. Let us see some example programs in C# to demonstrate Encapsulation by those two methods. The first method is using a pair of conventional accessor and mutator methods. Another one method is using a named property. Whatever be the method our aim is to use the data without any damage or change.
193
194ENCAPSULATION USING ACCESSORS AND MUTATORS
195
196Let us see an example of Department class. To manipulate the data in that class (String departname) we define an accessor (get method) and mutator (set method).
197using system;
198public class Department
199{
200 private string departname;
201 .......
202 // Accessor.
203 public string GetDepartname()
204 {
205 return departname;
206 }
207 // Mutator.
208 public void SetDepartname(string a)
209 {
210 departname = a;
211 }
212}
213Like the above way we can protect the private data from the outside world. Here we use two separate methods to assign and get the required data.
214public static int Main(string[] args)
215{
216 Department d = new Department();
217 d.SetDepartname("ELECTRONICS");
218 Console.WriteLine("The Department is :" + d.GetDepartname());
219 return 0;
220}
221In the above example we can't access the private data departname from an object instance. We manipulate the data only using those two methods.
222
223For more follow the link:
224Encapsulation in C#
2255. Inheritance in C#
226
227Inheritance is one of the three foundational principles of Object-Oriented Programming (OOP) because it allows the creation of hierarchical classifications. Using inheritance you can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it.
228
229In the language of C#, a class that is inherited is called a base class. The class that does the inheriting is called the derived class. Therefore a derived class is a specialized version of a base class. It inherits all of the variables, methods, properties, and indexers defined by the base class and adds its own unique elements.
230
231Example
232
233Diagram
234
235The following diagram shows the inheritance of a shape class. Here the base class is Shape and the other classes are its child classes. In the following program we will explain the inheritance of the Triangle class from the Shape class.
236
237Diagram
238//Base class or Parent class.
239class Shape
240{
241 public double Width;
242 public double Height;
243 public void ShowDim()
244 {
245 Console.WriteLine("Width and height are " +
246 Width + " and " + Height);
247 }
248}
249// Triangle is derived from Shape.
250//Drived class or Child class.
251class Triangle: Shape
252{
253 public string Style; // style of triangle
254 // Return area of triangle.
255 public double Area()
256 {
257 return Width * Height / 2;
258 }
259 // Display a triangle's style.
260 public void ShowStyle() {
261 Console.WriteLine("Triangle is " + Style);
262 }
263 }
264 //Driver class which runs the program.
265class Driver
266{
267 static void Main()
268 {
269 Triangle t1 new Triangle();
270 Triangle t2 new Triangle();
271 t1.Width = 4.0;
272 t1.Height = 4.0;
273 t1.Style = "isosceles";
274 t2.Width = 8.0;
275 t2.Height = 12.0;
276 t2.Style = "right";
277 Console.WriteLine("Info for t1: ");
278 t1.ShowStyle();
279 t1.ShowDim();
280 Console.WriteLine("Area is " + t1.Area());
281 Console.WriteLine();
282 Console.WriteLine("Info for t2: ");
283 t2.ShowStyle();
284 t2.ShowDim();
285 Console.WriteLine("Area is " + t2.Area());
286 }
287}
288The output from this program is shown here:
289
290Info for t1
291Triangle is isosceles
292Width and height are 4 and 4
293Area is 8
294Info for t2:
295Triangle is right
296Width and height are 8 and 12
297Area is 48
298
299For more follow the link:
300Inheritance With Example in C#
3016. Polymorphism in C#
302
303Polymorphism means the same operation may behave differently on different classes.
304Example of Compile Time Polymorphism: Method Overloading
305
306Example of Run Time Polymorphism: Method Overriding
307
308Example of Compile Time Polymorphism
309
310Method Overloading: Method with same name but with different arguments is called method overloading.
311
312Method Overloading forms compile-time polymorphism.
313Example of Method Overloading
314class A1
315{
316 void hello()
317 {
318 Console.WriteLine("Hello");
319 }
320 void hello(string s)
321 {
322 Console.WriteLine("Hello {0}", s);
323 }
324}
325Example of Run Time Polymorphism
326Method Overriding: Method overriding occurs when child class declares a method that has the same type arguments as a method declared by one of its superclass.
327
328Method overriding forms Run-time polymorphism.
329
330Note
331
332By default functions are not virtual in C# and so you need to write “virtual†explicitly. While by default in Java each function are virtual.
333
334Example of Method Overriding
335Class parent
336{
337 virtual void hello()
338 {
339 Console.WriteLine("A D Patel");
340 }
341}
342Class child: parent
343{
344 override void hello()
345 {
346 Console.WriteLine("R A Patel");
347 }
348}
349static void main()
350 {
351 parent objParent = new child();
352 objParent.hello();
353 }
354 //Output
355R A Patel
356For more follow the link:
357Polymorphism in C#
3587. Delegates in C#
359
360Delegate is one of the base types in .NET. Delegate is a class, which is used to create delegate at runtime.
361
362Delegate in C# is similar to a function pointer in C or C++. It's a new type of object in C#. Delegate is very special type of object as earlier the entire the object we used to defined contained data but delegate just contains the details of a method.
363
364Need of delegate
365
366There might be a situation in which you want to pass methods around to other methods. For this purpose we create delegate.
367
368A delegate is a class that encapsulates a method signature. Although it can be used in any context, it often serves as the basis for the event-handling model in C# but can be used in a context removed from event handling (e.g. passing a method to a method through a delegate parameter).
369
370One good way of understanding delegates is by thinking of a delegate as something that gives a name to a method signature.
371
372Example
373public delegate int DelegateMethod(int x, int y);
374Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own-delegated method.
375
376This ability to refer to a method as a parameter makes delegates ideal for defining callback methods.
377
378Delegate magic
379
380In class we create its object, which is instance, but in delegate when we create instance that is also referred to as delegate (means whatever you do you will get delegate).
381
382Delegate does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.
383
384Benefit of delegates
385
386In simple words delegates are object oriented and type-safe and very secure as they ensure that the signature of the method being called is correct. Delegate helps in code optimization.
387
388Types of delegates
389Singlecast delegates
390Multiplecast delegates
391Delegate is a class. Any delegate is inherited from base delegate class of .NET class library when it is declared. This can be from either of the two classes from System.Delegate or System.MulticastDelegate.
392
393Singlecast delegate
394
395Singlecast delegate point to single method at a time. In this the delegate is assigned to a single method at a time. They are derived from System.Delegate class.
396
397Multicast Delegate
398
399When a delegate is wrapped with more than one method that is known as a multicast delegate.
400
401In C#, delegates are multicast, which means that they can point to more than one function at a time. They are derived from System.MulticastDelegate class.
402
403For more follow the link:
404C# Delegates
4058. Collections in C#
406
407“.NET†offers a variety of collections, such as ArrayList, Hashtable, queues, Dictionaries. Collections are abstractions of data algorithms. An ArrayList is an abstract dynamic array, a Hashtable collection abstracts a lookup table, a Queues collection abstracts queues and so on. In addition to that, collections implement the ICollection, IEnumerable and IClonable interfaces. The detailed specification for each collection is found under the System.Collection namespace.
408
409ArrayList Collection
410
411An ArrayList is a dynamic array and implements the IList interface. Each element is accessible using the indexing operator. While the traditional array has a fixed number of elements, in the case of Array List, elements can be added or removed at run time.
412
413We can create an object of ArrayList using a general type of syntax as follows;
414
415ArrayList obj = new ArrayList();
416
417Here you can use the new keyword to create an instance of the ArrayList object. You don't need to specify the size. Once you have an empty ArrayList object, you can use the Add() method to add elements to it,as in,
418obj.Add("item1");
419obj.Add("2");
420obj.Add("Delhi");
421Each new item in the ArrayList is added to the end of the list, so it has the largest index number. If you wanted to add an item in the middle of the list, then you can use "Insert()" with a numeric argument as follows,
422Obj.Insert(2,"item2");
423You can also remove members of the ArrayList using either Remove() or RemoveAt() methods as in the following,
424Obj.Remove("item1");
425Obj.RemoveAt(3);
426Benefits of ArrayLists
427Insert Elements: An ArrayList starts with a collection containing no elements. You can add them in any position as you choose them.
428
429Automatic Resizing: you do not need to specify the array size; as you add elements, the array automatically ensures there is enough memory for the array.
430
431Flexibility When Removing Elements: you can remove any element from an Arraylist very easily.
432Limitations of ArrayLists
433
434The flexibility of ArrayList comes at a cost of performance. Since memory allocation is a very expensive business, the fixed number of elements of the simple array makes it much faster to work with.
435
436Note - ArrayLists are slower and more resource-intensive than a conventional array.
437
438Simple ArrayList Example
439
440The following example shows an array list with an #ff0000 size. Elements are added dynamically as required. We are adding elements using the "Add()" method as well as using the "Insert()" method at a specific location. Later we are displaying all the elements by iterating through the list.
441using System;
442using System.Collections;
443namespace CollectionApp
444{
445 class Program
446 {
447 static void Main(string[] args)
448 {
449 //Defining an ArrayList
450 ArrayList obj = new ArrayList();
451 //Adding elements
452 obj.Add("India");
453 obj.Add("USA");
454 obj.Add("Russia");
455 obj.Add("300");
456 //Adding elements to specific position
457 obj.Insert(2, "Japan");
458 //Accessing elements
459 for (int i = 0; i < obj.Count; i++)
460 {
461 Console.WriteLine("At Index[" + i + "]= " + obj[i].ToString());
462 }
463 Console.WriteLine("____________");
464 Console.WriteLine("Press any key");
465 Console.ReadKey();
466 }
467 }
468}
469After building and running this program, the output of the program is as in the following,
470
471output
472
473For more Collections follow the link:
474Using .NET Collections With C#
4759. Exception handling in C#
476
477Exception handling is a built-in mechanism in .NET framework to detect and handle run time errors. The .NET framework contains many standard exceptions. The exceptions are anomalies that occur during the execution of a program. They can be because of user, logic or system errors. If a user (programmer) does not provide a mechanism to handle these anomalies, the .NET run time environment provides a default mechanism that terminates the program execution.
478
479C# provides the three keywords try, catch and finally to do exception handling. The try block encloses the statements that might throw an exception whereas catch handles an exception if one exists. The finally can be used for doing any clean-up process.
480
481The general form of try-catch-finally in C# is shown below.
482
483try
484{
485 // Statement which can cause an exception.
486} catch (Type x)
487{
488 // Statements for handling the exception
489} finally
490{
491 //Any cleanup code
492}
493If any exception occurs inside the try block then the control transfers to the appropriate catch block and later to the finally block.
494
495But in C#, both catch and finally blocks are optional. The try block can exist either with one or more catch blocks or a finally block or with both catch and finally blocks.
496
497If there is no exception occurring inside the try block then the control directly transfers to the finally block. We can say that the statements inside the finally block is executed always. Note that it is an error to transfer control out of a finally block by using break, continue, return or goto.
498
499In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate base class for any exceptions in C#. The C# itself provides a couple of standard exceptions. Or even the user can create their own exception classes, provided that this should inherit from either the Exception class or one of the standard derived classes of the Exception class like DivideByZeroExcpetion or ArgumentException and so on.
500
501For more follow the link:
502Exception Handling in C#
50310. File Handling in C#
504
505The System.IO namespace provides four classes that allow you to manipulate individual files, as well as interact with a machine directory structure. The Directory and File directly extends System.Object and supports the creation, copying, moving and deletion of files using various static methods. They only contain static methods and are never instantiated. The FileInfo and DirecotryInfo types are derived from the abstract class FileSystemInfo type and they are typically, employed for obtaining the full details of a file or directory because their members tend to return strongly typed objects. They implement roughly the same public methods as a Directory and a File but they are stateful and the members of these classes are not static.
506
507diagram
508
509In the .NET framework, the System.IO namespace is the region of the base class libraries devoted to file based input and output services. Like any namespace, the System.IO namespace defines a set of classes, interfaces, enumerations, structures and delegates. The following table outlines the core members of this namespace.
510
511Class Types Description
512Directory/ DirectoryInfo These classes support the manipulation of the system directory structure.
513DriveInfo This class provides detailed information regarding the drives that a given machine has.
514FileStream This gets you random file access with data represented as a stream of bytes.
515File/FileInfo These sets of classes manipulate a computer's files.
516Path It performs operations on System.String types that contain file or directory path information in a platform-neutral manner.
517BinaryReader/ BinaryWriter These classes allow you to store and retrieve primitive data types as binary values.
518StreamReader/StreamWriter Used to store textual information to a file.
519StringReader/StringWriter These classes also work with textual information. However, the underlying storage is a string buffer rather than a physical file.
520BufferedStream This class provides temp storage for a stream of bytes that you can commit to storage at a later time.
521The System.IO provides a class DriveInfo to manipulate the system drive related tasks. The DriveInfo class provides numerous details such as the total number of drives, calculation of total hard disk space, available space, drive name, ready status, types and so on. Consider the following program that shows the total disk drives.
522
523DriveInfo[] di = DriveInfo.GetDrives();
524Console.WriteLine("Total Partitions");
525
526foreach(DriveInfo items in di)
527{
528 Console.WriteLine(items.Name);
529}
530The following code snippets perform the rest of the DriveInfo class method operations in details. It displays specific drive full information.
531using System;
532using System.IO;
533
534namespace DiskPartition
535{
536 class Program
537 {
538 static void Main(string[] args)
539 {
540 DriveInfo[] di = DriveInfo.GetDrives();
541
542 Console.WriteLine("Total Partitions");
543 Console.WriteLine("---------------------");
544 foreach(DriveInfo items in di)
545 {
546 Console.WriteLine(items.Name);
547 }
548 Console.Write("\nEnter the Partition::");
549 string ch = Console.ReadLine();
550
551 DriveInfo dInfo = new DriveInfo(ch);
552
553 Console.WriteLine("\n");
554
555 Console.WriteLine("Drive Name::{0}", dInfo.Name);
556 Console.WriteLine("Total Space::{0}", dInfo.TotalSize);
557 Console.WriteLine("Free Space::{0}", dInfo.TotalFreeSpace);
558 Console.WriteLine("Drive Format::{0}", dInfo.DriveFormat);
559 Console.WriteLine("Volume Label::{0}", dInfo.VolumeLabel);
560 Console.WriteLine("Drive Type::{0}", dInfo.DriveType);
561 Console.WriteLine("Root dir::{0}", dInfo.RootDirectory);
562 Console.WriteLine("Ready::{0}", dInfo.IsReady);
563
564 Console.ReadKey();
565 }
566 }
567}
568After compiling this program, it displays nearly every detail of disk drives and a specific drive as in the following,
569
570cmd
571
572Reading and Writing to Files
573
574Reading and writing operations are done using a File object. The following code snippet reads a text file located in the machine somewhere.
575private void button1_Click(object sender, EventArgs e)
576{
577 try
578 {
579 textBox2.Text = File.ReadAllText(txtPath.Text);
580 } catch (FileNotFoundException)
581 {
582 MessageBox.Show("File not Found....");
583 }
584}
585Here, first the user interface asks the user to enter the path of the file that he wanted to display. Later that path is passed to the File method ReadAllText() method that reads all the text integrated in the file and displays it over the text box.
586
587Besides reading a file, we can write some contents over an existing text file by the File class WriteAllTest() method as in the following,
588File.WriteAllText(@"d:\test.txt", textBox2.Text);
589It takes a path to save the file and content input method medium such as a text box or any other control. The following images depict a text file reading by entering its corresponding path,
590
591read
592
593Stream
594
595The .NET provides many objects such as FileStream, StreamReader/Writer, BinaryReader/Writer to read from and write data to a file. A stream basically represents a chunk of data flowing between a source and a destination. Stream provides a common way to interact with a sequence of bytes regardless of what kind of devices store or display the bytes. The following table provides common stream member functions,
596
597Methods Description
598Read()/ ReadByte() Read a sequence of bytes from the current stream.
599Write()/WriteByte() Write a sequence of bytes to the current stream.
600Seek() Sets the position in the current stream.
601Position() Determine the current position in the current stream.
602Length() Return the length of the stream in bytes.
603Flush() Updates the underlying data source with the current state of the buffer and then clears the buffer.
604Close() Closes the current stream and releases any associated stream resources.
605FileStream
606
607A FileStream instance is used to read or write data to or from a file. In order to construct a FileStream, first we need a file that we want to access. Second, the mode that indicates how we want to open the file. Third, the access that indicates how we want to access a file. And finally, the share access that specifies whether you want exclusive access to the file.
608
609Enumeration Values
610FileMode Create, Append, Open, CreateNew, Truncate, OpenOrCreate
611FileAccess Read, Write, ReadWrite
612FileShare Inheritable, Read, None, Write, ReadWrite
613The FileStream can read or write only a single byte or an array of bytes. You will be required to encode the System.String type into a corresponding byte array. The System.Text namespace defines a type named encoding that provides members that encode and decode strings to an array of bytes. Once encoded, the byte array is persisted to a file with the FileStream.Write() method. To read the bytes back into memory, you must reset the internal position of the stream and call the ReadByte() method. Finally, you display the raw byte array and the decoded string to the console.
614
615using(FileStream fs = new FileStream(@ "d:\ajay123.doc", FileMode.Create))
616{
617 string msg = "first program";
618 byte[] byteArray = Encoding.Default.GetBytes(msg);
619 fs.Write(byteArray, 0, byteArray.Length);
620 fs.Position = 0;
621
622 byte[] rFile = new byte[byteArray.Length];
623
624 for (int i = 0; i < byteArray.Length; i++)
625 {
626 rFile[i] = (byte) fs.ReadByte();
627 Console.WriteLine(rFile[i]);
628 }
629
630 Console.WriteLine(Encoding.Default.GetString(rFile));
631}
632BinaryReader and BinaryWriter
633
634The BinaryReader and Writer class allows you to read and write discrete data types to an underlying stream in a compact binary format. The BinaryWriter class defines a highly overloaded Write method to place a data type in the underlying stream.
635
636Members Description Class
637Write Write the value to current stream BinaryWriter
638Seek Set the position in the current stream BinaryWriter
639Close Close the binary reader BinaryWriter
640Flush Flush the binary stream BinaryWriter
641PeekChar Return the next available character without advancing the position in the stream BinaryReader
642Read Read a specified set of bytes or characters and store them in the incoming array. BinaryReader
643For more examples follow the link:
644
645File Handling in C# .NET
646Thanks for following this article and stay tuned for more new articles.
647
648Connect (“Nitin Panditâ€)
649Further Recommendations
650
651Want more on C#? Here is list of recommended resources.
652Programming C# for Beginners
653Programming C# 5.0
654New Features in C# 6.0
655Programming Dictionary in C#
656Working with Directories in C#
657Programming Dictionary in C#
658Article Extensions
659
660Versatility
661One of the key features of C# language is its versatility. Although, it is not a language feature but more like a platform feature but C# language can used to build variety of software systems. Obviously, you can use C# to build Windows based systems including console apps, Windows client apps, Windows services, back-end jobs and services and so on. C# can be used to build mobile and enterprise systems. But most importantly, with the help of Xamarin, C# can also be used to build mobile apps to target all three major platforms, iOS, Android, and Windows Mobile.