0% found this document useful (0 votes)
14 views

Unit-3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Unit-3

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

C# Concepts for creating Data Structures File Operation

Generally, the file is used to store the data. The term File Handling refers to the
various operations like creating the file, reading from the file, writing to the file,
appending the file, etc. There are two basic operations which is mostly used in
file handling is reading and writing of the file. The file becomes stream when we
open the file for writing and reading. A stream is a sequence of bytes which is
used for communication. Two stream can be formed from file one is input stream
which is used to read the file and another is output stream is used to write in the
file. In C#, System.IO namespace contains classes which handle input and output
streams and provide information about file and directory structure.
StreamWriter Class
The StreamWriter class implements TextWriter for writing character to stream
in a particular format. The class contains the following method which are
mostly used.
Method Description
 Close() -Closes the current StreamWriter object and stream associate
with it.
 Flush()-Clears all the data from the buffer and write it in the stream
associate with it.
 Write()-Write data to the stream. It has different overloads for different
data types to write in stream.
 WriteLine()-It is same as Write() but it adds the newline character at the
end of the data.
Eg: - // C# program to write user input
// to a file using StreamWriter Class
using System;
using System.IO;
namespace GeeksforGeeks {
class GFG {
class WriteToFile
{
public void Data()
{
// This will create a file named sample.txt
// at the specified location
StreamWriter sw = new StreamWriter("H://week.txt");
// To write on the console screen
Console.WriteLine("Enter the Text that you want to write on File");
// To read the input from the user
string str = Console.ReadLine();
// To write a line in buffer
sw.WriteLine(str);
// To write in output stream
sw.Flush();
// To close the stream
sw.Close();
}
}
// Main Method
static void Main(string[] args)
{
WriteToFile wr = new WriteToFile();
wr.Data();
Console.ReadKey();
}
}
}

StreamReader Class
The StreamReader class implements TextReader for reading character from the
stream in a particular format. The class contains the following method which are
mostly used.
Method Description
 Close() -Closes the current StreamReader object and stream
associate with it.
 Peek()-Returns the next available character but does not consume it.
 Read()-Reads the next character in input stream and increment characters
position by one in the stream
 ReadLine()-Reads a line from the input stream and return the data in
form of string
 Seek()-It is use to read/write at the specific location from a file
Eg: - // C# program to read from a file
// using StreamReader Class
using System;
using System.IO;
namespace GeeksforGeeks {
class GFG {
class ReadFile {
public void DataReading()
{
// Takinga a new input stream i.e.
// geeksforgeeks.txt and opens it
StreamReader sr = new StreamReader("H://week.txt");

Console.WriteLine("Content of the File");

// This is use to specify from where


// to start reading input stream
sr.BaseStream.Seek(0, SeekOrigin.Begin);

// To read line from input stream


string str = sr.ReadLine();

// To read the whole file line by line


while (str != null)
{
Console.WriteLine(str);
str = sr.ReadLine();
}
Console.ReadLine();

// to close the stream


sr.Close();
}
}
// Main Method
static void Main(string[] args)
{
ReadFile wr = new ReadFile();
wr.DataReading();
}
}
}

File Management systems


C# includes static File class to perform I/O operation on physical file system. The
static File class includes various utility method to interact with physical file of
any type e.g. binary, text etc. Use this static File class to perform some quick
operation on physical file. It is not recommended to use File class for multiple
operations on multiple files at the same time due to performance reasons. Use
FileInfo class in that scenario.
Method and Usage
 AppendAllLines: Appends lines to a file, and then closes the file. If the
specified file does not exist, this method creates a file, writes the specified
lines to the file, and then closes the file.
 AppendAllText: Opens a file, appends the specified string to the file, and
then closes the file. If the file does not exist, this method creates a file,
writes the specified string to the file, then closes the file.
 AppendText: Creates a StreamWriter that appends UTF-8 encoded text to
an existing file, or to a new file if the specified file does not exist.
 Copy: Copies an existing file to a new file. Overwriting a file of the same
name is not allowed.
 Create: Creates or overwrites a file in the specified path.
 CreateText: Creates or opens a file for writing UTF-8 encoded text.
 Decrypt: Decrypts a file that was encrypted by the current account using
the Encrypt method.
 Delete: Deletes the specified file.
 Encrypt: Encrypts a file so that only the account used to encrypt the file
can decrypt it.
 Exists: Determines whether the specified file exists.
 GetAccessControl: Gets a FileSecurity object that encapsulates the access
control list (ACL) entries for a specified file.
 Move: Moves a specified file to a new location, providing the option to
specify a new file name.
 Open: Opens a FileStream on the specified path with read/write access.
 ReadAllBytes: Opens a binary file, reads the contents of the file into a byte
array, and then closes the file.
 ReadAllLines: Opens a text file, reads all lines of the file, and then closes
the file.
 ReadAllText: Opens a text file, reads all lines of the file, and then closes
the file.
 Replace: Replaces the contents of a specified file with the contents of
another file, deleting the original file, and creating a backup of the replaced
file.
 WriteAllBytes: Creates a new file, writes the specified byte array to the
file, and then closes the file. If the target file already exists, it is
overwritten.
 WriteAllLines: Creates a new file, writes a collection of strings to the file,
and then closes the file.
 WriteAllText: Creates a new file, writes the specified string to the file,
and then closes the file. If the target file already exists, it is overwritten.
Eg:- public object FileSystem(FileSystemCommand command, string
arguments)
{
// Configure File System Options
var config = new FileSystemConfiguration
{
Request = Request,
FileSystemProvider = new
PhysicalFileSystemProvider(hostingEnvironment.ContentRootPath +
"/wwwroot"),
AllowDownload = true,
AllowUpload = true,
UploadConfiguration = new UploadConfiguration
{
MaxFileSize = 1048576
},
};
}

Stream Oriented Operations- Multitasking


Multitasking refers to allowing the user to perform multiple tasks at the same
time. The user can listen to music running in the background, while writing a
blog. Hence, the computer is performing multiple tasks for the user. Each task
requires resources. Since the computer has limited resources, the number of tasks
performed at the same time are also limited.

Multithreading – Thread Operation

Multithreading is used to perform multiple tasks. Each task can have multiple
threads. In a multithreaded application, the user can do more in a short span of
time than a single thread application. Today, almost every application uses
multiple threading. An application or a process can have a user interface thread
that manages interactions with the user and background worker threads that
perform other tasks.

Add the following namespace: -


using System.Threading;
using System.Threading.Tasks;
Eg: -1.
Eg: -2.
Synchronization in C#
Synchronization in C# is a mechanism that makes sure only one process or thread
accesses the critical section of the program. All the other threads have to wait
until the critical section is free before they can enter it. Data inconsistency occurs
when more than one threads access a shared resource such as in-memory data
(instance or class variables) and external objects such as files at the same time.
Let us understand this with an example. Consider that we have two threads
Thread1 and Thread2, and both the threads access a shared resource let’s say
Resource1 simultaneously. If Thread1 is trying to read data from the shared
resource Resource1 when Thread2 is attempting to write data onto the shared
resource Resource1, then there would be data inconsistency. Hence, in situations
like this thread synchronization comes into the picture.

Synchronization in C# language is a process that allows access to shared


resources smoothly. Synchronization in C# ensures that only one thread is
accessing the shared resource at any given point in time, preventing other threads
from doing the same at the same time. Thread Synchronization in C# is a
mechanism that is used to restrict multiple threads from accessing a shared
resource at the same time. In simple words, we can also say that thread
synchronization can help us to prevent multiple threads from gaining access to a
shared resource simultaneously. As a result, we can have one and only one thread
entering a critical section to access the shared resource at any given point in time.

Some of the advantages of thread synchronization is given as follows:


 Synchronization can be used to achieve mutual exclusion i.e. only one
process or thread accesses the critical section of the program.
 No thread or process has an infinite waiting time using synchronization.
 Synchronization is an inherently fair process.
 All the requests are granted in a specific order using synchronization.
 Synchronization can be used for resource allocation as well. It makes sure
that only one process or thread can use a resource at a time.
Eg: - 1.
using System;
using System.Threading;
namespace ThreadStateDemo
{
class Program
{
static void Main(string[] args)
{
Thread thread1 = new Thread(SomeMethod)
{
Name = "Thread 1"
};
Thread thread2 = new Thread(SomeMethod)
{
Name = "Thread 2"
};
Thread thread3 = new Thread(SomeMethod)
{
Name = "Thread 2"
};
thread1.Start();
thread2.Start();
thread3.Start();
Console.ReadKey();
}
public static void SomeMethod()
{
Console.Write("[Welcome To The ");
Thread.Sleep(1000);
Console.WriteLine("World of Dotnet!]");
}
}
}
Eg: - 2.
using System;
using System.Threading;
namespace ThreadStateDemo
{
class Program
{
static object lockObject = new object();
static void Main(string[] args)
{
Thread thread1 = new Thread(SomeMethod)
{
Name = "Thread 1"
};
Thread thread2 = new Thread(SomeMethod)
{
Name = "Thread 2"
};
Thread thread3 = new Thread(SomeMethod)
{
Name = "Thread 2"
};
thread1.Start();
thread2.Start();
thread3.Start();
Console.ReadKey();
}
public static void SomeMethod()
{
// Locking the Shared Resource for Thread Synchronization
lock (lockObject)
{
Console.Write("[Welcome To The ");
Thread.Sleep(1000);
Console.WriteLine("World of Dotnet!]");
}
}
}
}
Eg: - 3.
using System;
using System.Threading;
namespace ThreadStateDemo
{
class Program
{
static void Main(string[] args)
{
BookMyShow bookMyShow = new BookMyShow();
Thread t1 = new Thread(bookMyShow.TicketBookig)
{
Name = "Thread1"
};
Thread t2 = new Thread(bookMyShow.TicketBookig)
{
Name = "Thread2"
};
Thread t3 = new Thread(bookMyShow.TicketBookig)
{
Name = "Thread3"
};
t1.Start();
t2.Start();
t3.Start();
Console.ReadKey();
}
}
public class BookMyShow
{
int AvailableTickets = 3;
static int i = 1, j = 2, k = 3;
public void BookTicket(string name, int wantedtickets)
{
if (wantedtickets <= AvailableTickets)
{
Console.WriteLine(wantedtickets + " booked to " + name);
AvailableTickets = AvailableTickets - wantedtickets;
}
else
{
Console.WriteLine("No tickets Available to book");
}
}
public void TicketBookig()
{
string name = Thread.CurrentThread.Name;
if (name.Equals("Thread1"))
{
BookTicket(name, i);
}
else if (name.Equals("Thread2"))
{
BookTicket(name, j);
}
else
{
BookTicket(name, k);
}
}
}
}
Eg: - 4.
using System;
using System.Threading;
namespace ThreadStateDemo
{
class Program
{
static void Main(string[] args)
{
BookMyShow bookMyShow = new BookMyShow();
Thread t1 = new Thread(bookMyShow.TicketBookig)
{
Name = "Thread1"
};
Thread t2 = new Thread(bookMyShow.TicketBookig)
{
Name = "Thread2"
};
Thread t3 = new Thread(bookMyShow.TicketBookig)
{
Name = "Thread3"
};

t1.Start();
t2.Start();
t3.Start();
Console.ReadKey();
}
}
public class BookMyShow
{
private object lockObject = new object();
int AvailableTickets = 3;
static int i = 1, j = 2, k = 3;
public void BookTicket(string name, int wantedtickets)
{
lock(lockObject)
{
if (wantedtickets <= AvailableTickets)
{
Console.WriteLine(wantedtickets + " booked to " + name);
AvailableTickets = AvailableTickets - wantedtickets;
}
else
{
Console.WriteLine("No tickets Available to book");
}
}
}
public void TicketBookig()
{
string name = Thread.CurrentThread.Name;
if (name.Equals("Thread1"))
{
BookTicket(name, i);
}
else if (name.Equals("Thread2"))
{
BookTicket(name, j);
}
else
{
BookTicket(name, k);
}
}
}
}

You might also like