0% found this document useful (0 votes)
30 views49 pages

Chapter 5 - Manipulating File

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views49 pages

Chapter 5 - Manipulating File

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Chapter Five

Manipulating Files

Event Driven Programming Jun 21, 2024


Introduction

Jun 21, 2024


 Up until now, any stored data within a program is lost when
the program closes
 A file is a permanent way to store data
 Several times you need to save information on a disk.
 You may not get database everywhere, and may require saving
information in a txt, doc, xls, pdf files or any other file types

Event Driven Programming


 C# has an extensive set of classes for handling files of
various types
 found in the System.IO namespace
 System.IO Namespace:-
 Collection of classes, methods, enumeration and types that is
responsible for reading & writing files and data streams
 All the File Handling operations require it.
 read & write files, stream and string, directory info and file info. 2
Introduction

Jun 21, 2024


 System.IO classes are used to work with files and streams
 File – block of information stored on disk or another media
 Text file – file that contains lines of written information that can be sent
directly to the screen or printer

Event Driven Programming


 Binary file – file that contains bits that do not necessarily represent
printable text. Examples: Word file, machine language file
 You can work with two kinds of files – txt files (containing only characters)
and binary files

3
What is File Handling in C#?

Jun 21, 2024


 .NET provides many objects such as FileStream,
StreamReader/Writer, BinaryReader/Writer to read from
and write data to file
 File handling :- is to save the information permanently on
the disk or reading information from the saved file
 uses a stream to save or retrieve information

Event Driven Programming


 Basic Terms
 Data maintained in files is called persistent data
 Smallest data item that computers support is called bit
 Digits, letters and special symbols are characters
 Bytes are composed of eight bits
 As characters are composed of bits, fields are composed of
characters 4
Contd…

Event Driven Programming Jun 21, 2024


Contd…

Jun 21, 2024


 Field - group of characters that conveys meaning
 single piece of data for the subject of the record
 Record - composed of several related fields
 File - collection of data /related records/ stored on a disk with a
specific name, extension and directory path
 used for long-term retention of large amounts of data, even after the

Event Driven Programming


program that created the data terminates
 when file is opened for reading or writing, becomes stream
 Stream - sequence of bytes traveling from a source to a
destination over a communication path
 two basic streams are:
 Input stream – used to for read data/byte stream from file
 Output stream – used to write data/byte stream into the file
 For both stream objects are created from class FileStream 6
Contd… keyboard

Jun 21, 2024


standard
input stream
CPU
standard
output MEM
monitor stream

Event Driven Programming


terminal
console

HDD
What does information
travel across?
Streams 7
Contd…

Jun 21, 2024


standard
input stream
keyboard CPU
standard
output MEM
monitor stream
terminal file
console

Event Driven Programming


input
stream
LOAD HDD
What does information READ
travel across? file
files output
Streams
stream
SAVE
WRITE 8
Contd…

Jun 21, 2024


FileStream object
byte stream

Event Driven Programming


FileStream object
byte stream

9
C# IO Classes

Jun 21, 2024


 System.IO namespace allow reading and writing to files
and data streams, and types that provide basic file and
directory support
 provides various classes for file handling
 The parent class of file processing is stream.
 Stream is an abstract class, which is used as the parent of the

Event Driven Programming


classes that actually implement the necessary operations.
• Note: FileInfo, DirectoryInfo and DriveInfo classes have
instance methods and File, Directory, Path classes have
static methods
• The following are some commonly used classes in the
System.IO namespace 10
Contd…

Jun 21, 2024


commonly used System.IO classes
Class Name Description
for random file access (read from & write to) with data represented as
FileStream
a stream of bytes to any location within a file.
BinaryReader/
used to read and write primitive data types from a binary stream
BinaryWriter
StreamReader/
used to read characters from a byte and write characters to a Stream

Event Driven Programming


StreamWriter
StreamWriter used to write characters to a stream.
StringReader/
used to read from and write into a string buffer
StringWriter
File/FileInfo sets of classes manipulate computer's files.
DirectoryInfo to perform operations on directories
Path It performs operations on System.String types that contain file or
directory path information in a platform-neutral manner.
11
File Manipulation Activities

Jun 21, 2024


 Open a file.
 Reading a file.
 Writing a file.
 Appending a text to a file.

Event Driven Programming


 Copying a file.
 Moving a file.
 Deleting a file.
12
Contd…

Jun 21, 2024


 Ability to open up a text file and read its
contents can be very useful in any programming
life
 Classes allow an application to obtain
information about files and directories stored on

Event Driven Programming


disc
 Aid in copying, moving, renaming,
creating, opening, deleting, and appending
files
13
Files and Streams

Jun 21, 2024


 When file is opened C#:
 Creates an object
 Associates a stream with that object
 Namespace System.IO needed for file processing
 System.IO.Stream: allows representation of stream as

Event Driven Programming


bits
 FileStream: read to and write from sequential access and
reandom-access files
 MemoryStream: transfer of data directly to and from
memory
 BufferedStream: uses buffer to transfer to memory 14
FileStream Class

Jun 21, 2024


 helps in reading from, writing to & closing files
 to use FileStream class, need to include System.IO
 create FileStream Object to create a new file or open an existing file
 enclose file handling code in a try{} catch{} clause
 In .NET Framework we often access files via streams
 We can place one stream on top of another (usually with "using"

Event Driven Programming


statements).
 Syntax:
FileStream <object_name> = new FileStream(<file_name>,
<FileMode Enumerator>, <FileAccess Enumerator>, <FileShare
Enumerator>);
 Example:
FileStream F = new FileStream("sample.txt",
FileMode.Open, FileAccess.Read, FileShare.Read); 16
Contd…

Jun 21, 2024


 FileMode – It specifies how to operation system should
open the file. It has following members
1. Append - Open the file if exist or create a new file. If file
exists then place cursor at the end of the file.
2. Create - It specifies operating system to create a new file. If
file already exists then previous file will be overwritten.

Event Driven Programming


3. CreateNew - It create a new file and If file already exists then
throw IOException.
4. Open – Open existing file.
5. Open or Create – Open existing file and if file not found then
create new file.
6. Truncate – Open an existing file and cut all the stored data. So
the file size becomes 0.
17
Contd…

Jun 21, 2024


 FileAccess – gives permission to file whether it will open
for Read, ReadWrite or Write mode
 FileShare – opens file with following share permission
1. Delete – Allows subsequent deleting of a file.
2. Inheritable – It passes inheritance to child process.

Event Driven Programming


3. None – It declines sharing of the current files.
4. Read- It allows subsequent opening of the file for
reading.
5. ReadWrite – It allows subsequent opening of the file for
reading or writing.
6. Write – Allows subsequent opening of the file for
writing.
18
StreamReader & Writer Classes

Jun 21, 2024


 used for reading from & writing data to text files
 derived/inherited from TextReader & TextWriter class
 use Read() & Write() methods for doing formatted I/O
 StreamReader Class
 to read series of characters/text from the file easily
 Use System.IO namespace for it

Event Driven Programming


 supplies several constructors, like:
public StreamReader (Stream stream);
FileStream fs = new FileStream(@"C:\Sample.txt",
FileMode.OpenOrCreate, FileAccess.Read);
using (StreamReader redr = new StreamReader (fs)) {
textBox1.Text = redr.ReadToEnd();
}
 ReadToEnd() method reads the stream from the current position to the end of
the stream. 19
Contd…

Jun 21, 2024


 StreamWriter Class
 more popular in File Handling
 easy to use and provides a complete set of constructors and
methods to work
 has several constructors and provides many methods; one of the
constructors takes:

Event Driven Programming


public StreamWriter(Stream stream)
 very helpful to write or append strings/text to a text file
 best placed in a using statement to ensure that the resources can
be removed when no longer needed
string file = @"D:\ Sample.txt";
using (StreamWriter writer = new StreamWriter(file))
{

}
writer.Write("Hellow StreamWriter");
20
Contd…

Jun 21, 2024


FileStream fs = new FileStream(file,
FileMode.OpenOrCreate, FileAccess.Write);
using (StreamWriter writer = new StreamWriter(fs))
{
writer.Write("Sample Text");
}
 StreamWriter Close()

Event Driven Programming


 If we did not specify the using statement then you should
manually dispose and close the StreamWriter using the Close
method:
FileStream fs = new FileStream((@"C:\Sample.txt",
FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(fs);
writer.Write("This is the sample text.");
writer.Close(); 21
Example: Create and Write to file

Jun 21, 2024


string fileName = ???
if (File.Exists(fileName))
{
try {
StreamReader stream = new StreamReader (fileName);
string inputString = stream.ReadToEnd();
}
catch (IOException)

Event Driven Programming


{
MessageBox.Show (“File Error”, “File Error”,
MessageBoxButtons.Ok, MessageBoxIcon..Error);
}
}
else
{
MessageBox.Show (fileName + “ does not exist”, “File Error”, MessageBoxButtons.Ok,
MessageBoxIcon..Error);
} 22
Example: Create and Write to file

Jun 21, 2024


• Create or Open a file
// Using Open method of the System.IO.FileInfo class.
FileInfo fileInfo = new FileInfo("New.txt");
FileStream fileStream = fileInfo.Open(FileMode.Append,
FileAccess.Write); OR
//Using the static Open method of System.IO.File class.
FileStream fileStream = File.Open("New.txt", FileMode.Append,

Event Driven Programming


FileAccess.Write); OR
//Using the System.IO.FileStream constructors. FileStream
fileStream = new FileStream("New.txt", FileMode.Append,
FileAccess.Write);
// Encapsulate the filestream object in a StreamWriter
instance.
StreamWriter fileWriter = new StreamWriter(fileStream);
• Write text to the file
fileWriter.WriteLine(txtStringtowrit.Text );
fileWriter.Close(); 23
Example: Read from file

Jun 21, 2024


• Read text from G3_IT_File file

FileStream fs = new FileStream("G3_IT_File.txt“,


FileMode.Open, FileAccess.Read);
using (StreamReader sr = new StreamReader(fs))

Event Driven Programming


{
txtStringreadfromFile.Text = sr.ReadToEnd();
}

24
TextReader & TextWriter Classes

Jun 21, 2024


 TextReader read sequential series of Characters
 a base class for StreamReader & StringReader classes
 StreamReader – used to read characters from a
stream
 StringReader – used to read characters from a string

Event Driven Programming


 is abstract class that means you cannot instantiate it
 After finishing reading or writing file you
must dispose or clean memory directly or indirectly.
 To directly dispose, call Dispose Method
in try/catch block and for indirectly disposal write code
inside using block
 use either StreamReader or StringReader to read text 25
Contd…

Jun 21, 2024


//Read One Line
using(TextReader tr=File.OpenText("1123.txt"))
{
txtStringtowrit.Text = tr.ReadLine();
}

Event Driven Programming


//Read full file
using (TextReader tr = File.OpenText(filepath))
{
tr.Write(tr.ReadToEnd());
}

26
Contd…

Jun 21, 2024


 Let us see some of the main members of the abstract class
TextReader
 Read() -- Reads data from an input stream.
 ReadLine() -- reads a line of characters from the current stream and returns
the data as a string.
 ReadBlock() – reads a maximum of count characters from the current
stream, and writes the data to buffer, beginning at index

Event Driven Programming


 ReadToEnd() -- Reads all characters from current position to the end of
the TextReader and returns them as one string.
using (StreamReader sr = new StreamReader(@"C:\123\sample.txt"))
{
String line;
while ((line = sr.ReadLine()) != null) {
MessageBox.Show(line);
}
} 27
Contd…

Jun 21, 2024


 Let us see some of the main members of the abstract class
TextReader
 Read() -- Reads data from an input stream.
 ReadLine() -- reads a line of characters from the current stream and returns
the data as a string.
 ReadBlock() – reads a maximum of count characters from the current
stream, and writes the data to buffer, beginning at index

Event Driven Programming


 ReadToEnd() -- Reads all characters from current position to the end of
the TextReader and returns them as one string.
using (StreamReader sr = new StreamReader(@"C:\123\sample.txt"))
{
String line;
while ((line = sr.ReadLine()) != null) {
MessageBox.Show(line);
}
} 28
TextReader & TextWriter Classes

Jun 21, 2024


 TextWriter class represents a writer that can write
sequential series of characters
 use this class to write text in a file.
 write characters to streams and string respectively

Event Driven Programming


using (TextWriter writer = File.CreateText(@"D:\
csharpfile.txt")) {
writer.Write("File Handling Tutorial");
writer.Write(“Thanks");
}
MessageBox.Show("Entry stored successfull!");

29
StringReader and StringWriter

Jun 21, 2024


 Used to treat textual information as a stream of in-memory
characters
 Helpful when you wish to append character-based information to an
underlying buffer
 StringWriter – used to manipulate string than files
 You can write a character with Write(Char) method and writer string

Event Driven Programming


with Write(String) method
 is not for writing files on local disk
 used for manipulate string and it saves information in StringBuilder
StringWriter wr = new StringWriter();
wr.Write("Friendship is not a two way road.");
wr.Write("It is a one way road travelled by two people.");
wr.close();
MessageBox.Show("Data: “ + wr.ToString()); 30
Contd…

Jun 21, 2024


 StringReader class implements TextReader class that
reads string from string.
 enables you to read a string synchronously or asynchronously
 read a character with Read() method and read a line
with ReadLine() method.

Event Driven Programming


string text = @"You are reading";
using (StringReader reader = new StringReader(text))
{
int count = 0;
string line;
while ((line = reader.ReadLine()) != null)
{
count++;
MessageBox.Show("Line : “ + line + “ and ” + count);
}
} 31
BinaryReader and BinaryWriter

Jun 21, 2024


 BinaryReader and BinaryWriter class allows you to read and
write discrete data types to an underlying stream in a compact
binary format.
 BinaryWriter class defines a highly overloaded Write method to
place a data type in the underlying stream.
Members Description Class

Event Driven Programming


Write Write the value to current stream BinaryWriter
Seek Set the position in the current stream BinaryWriter
Close Close the binary reader BinaryWriter
Flush Flush the binary stream BinaryWriter
PeekChar Return the next available character without BinaryReader
advancing the position in the stream
Read Read a specified set of bytes or characters and BinaryReader
store them in the incoming array.
32
Contd…

Jun 21, 2024


// writing
FileInfo fi = new FileInfo(“123.txt");
using (BinaryWriter bw = new BinaryWriter(fi.OpenWrite()))
{
int x = 007;
string str = "hello G3 IT";
bw.Write(x);

Event Driven Programming


bw.Write(str);
}
//Reading
FileInfo f = new FileInfo("champu.dat");
using (BinaryReader br = new BinaryReader(fi.OpenRead()))
{
MessageBox.Show(br.ReadInt32());
MessageBox.Show(br.ReadString());
} 33
Directory and File Class

Jun 21, 2024


• File Classes – using for the File operations in C#
 create, delete, copy, etc. operations do with C# File class
 In order to create a new File using C# File class , we can call Create
method in the File class
Syntax : FileStream File.Create(string FilePath)
FilePath : The name of the new File Object
File.Create("c:\\testFile.txt");

Event Driven Programming


 only contain static methods and are never instantiated
• How to check a File exist or not
 Before we creating a File object, we usually check that File exist or not, use
Exists method in the C# File class
Syntax : bool File.Exists(string FilePath)
FilePath : The name of the File
bool : Returns true or false –
if File exist it Returns true else Returns false
File.Exists("c:\\testFile.txt") 34
Contd…

Jun 21, 2024


if (File.Exists("c:\\testFile.txt"))
{
MessageBox.Show ("File 'testFile’ already Exist");
}
else
{

Event Driven Programming


File.Create("c:\\testFile.txt");
MessageBox.Show("File 'testFile' created ");
}
OR FileStream fs = null;
if (!File.Exists(fileLoc))
{
using (fs = File.Create(fileLoc))
{
}
} 35
Contd…

Jun 21, 2024


How to copy a File?
use Copy method in the File class
string fileLocCopy = @"d:\sample1.txt";
if (File.Exists(fileLoc))

Event Driven Programming


{
// If file already exists in destination, delete it.
if (File.Exists(fileLocCopy))
File.Delete(fileLocCopy);
File.Copy(fileLoc, fileLocCopy);
}
36
Contd…

Jun 21, 2024


• Directory Classes supports the creation, copying,
moving and deletion of folders
 they only contain static methods and are never
instantiated
 exposes methods to create, delete, move etc. operations

Event Driven Programming


to directories and subdirectories
 because of the static nature of Directory class , we do
not have to instantiate the class
 call the methods in the Directory class directly from the
Directory class itself

37
Contd…

Jun 21, 2024


• How to create a directory?
 Call CreateDirectory method directly from Directory
class
Syntax : Directory.CreateDirectory(string DirPath)
DirPath : The name of the new directory

Event Driven Programming


Directory.CreateDirectory("c:\\testDir1");
• How to check a directory exist or not ?
 Use Exists method in the Directory class
Syntax : bool Directory.Exist(string DirPath)
DirPath : The name of the directory
bool : Returns true or false –
if directory exist it Returns true , else it Returns false
Directory.Exists("c:\\testDir1") 38
Contd…

Jun 21, 2024


• How to move a Directory? – to move a directory and its
contents from one location to another
 use Move method in the Directory class
Syntax : void Directory.Move(string sourceDirName,string
destDirName)

Event Driven Programming


sourceDirName : The source directory we want to move
destDirName : The destinations directory name
Directory.Move("c:\\testDir1\\testDir2", "c:\\testDir");
• How to delete a directory ?
 use Delete method in the C# Directory class
Syntax : void Directory.Delete(string DirPath)
DirPath : The Directory we want to delete.
Directory.Delete("c:\\testDir1"); 39
Contd…

Jun 21, 2024


if (Directory.Exists("c:\\testDir1"))
{
//shows message if testdir1 exist
MessageBox.Show ("Directory 'testDir' Exist ");
}
else {
//create the directory testDir1 Directory.CreateDirectory("c:\\testDir1");

Event Driven Programming


MessageBox.Show("testDir1 created ! ");
//create the directory testDir2 Directory.CreateDirectory("c:\\testDir1\\testDir2");
MessageBox.Show("testDir2 created ! ");
//move the directory testDir2 as testDir in c:\ Directory.Move("c:\\testDir1\\testDir2",
"c:\\testDir"); MessageBox.Show("testDir2 moved ");
//delete the directory testDir1
Directory.Delete("c:\\testDir1");
MessageBox.Show("testDir1 deleted ");
}
40
DirectoryInfo Class

Jun 21, 2024


• typically, employed for obtaining the full details
of a file or directory
 has various static methods for creating, reading,
copying, moving, and deleting files using the
FileStream objects through directories and

Event Driven Programming


subdirectories.
 cannot be inherited

41
Contd…

Jun 21, 2024


 commonly used properties of DirectoryInfo class
S.N Property Name & Description
1 Attributes
Gets the attributes for the current file or directory.
2 CreationTime
Gets the creation time of the current file or directory.

Event Driven Programming


3 Exists
Gets a Boolean value indicating whether the directory exists.
4 Extension
Gets the string representing the file extension.
5 FullName
Gets the full path of the directory or file.
6 LastAccessTime
Gets the time the current file or directory was last accessed.
7 Name
Gets the name of this DirectoryInfo instance. 42
Contd…

Jun 21, 2024


 commonly used methods of DirectoryInfo class
S.N Method Name & Purpose
1 public void Create()
Creates a directory.
2 public DirectoryInfo CreateSubdirectory( string path )

Event Driven Programming


Creates a subdirectory or subdirectories on the specified path. The
specified path can be relative to this instance of the DirectoryInfo class.

3 public override void Delete()


Deletes this DirectoryInfo if it is empty.
4 public DirectoryInfo[] GetDirectories()
Returns the subdirectories of the current directory.
5 public FileInfo[] GetFiles()
Returns a file list from the current directory.
43
Contd…

Jun 21, 2024


 DriveInfo class displays specific drive full information
DirectoryInfo di=new DirectoryInfo(@"D:\temp");
MessageBox.Show("***Direcotry Informations***\n “ +
"Full Name= “ + di.FullName + "Root= “ + di.Root +
"Attributes= “ + di.Attributes + "Creation Time= “
+ di.CreationTime + "Name= “ + di.Name + "Parent= “

Event Driven Programming


+ di.Parent);
Note:
 Typically, we make the assumption that the path passed in the constructor of
the DirectoryInfo class physically exists.
 However, if you attempt to interact with a nonexistent directory then the
CLR will throw an exception.
 So, need to create a directory first to handle the exceptions
DirectoryInfo di=new DirectoryInfo(@"D:\temp\xyz");
di.Create(); 44
FileInfo Class

Jun 21, 2024


• Typically, employed for obtaining the full
details of a file or directory
 has various static methods for creating, reading,
copying, moving, and deleting files using the
FileStream objects through directories and

Event Driven Programming


subdirectories.
 cannot be inherited

45
Contd…

Jun 21, 2024


 Commonly used properties of FileInfo class are:
S.N Property Name & Description
1 Attributes
Gets the attributes for the current file.
2 CreationTime
Gets the creation time of the current file.
3 Directory
Gets an instance of the directory which the file belongs to.
4

Event Driven Programming


Exists
Gets a Boolean value indicating whether the file exists.
5 Extension
Gets the string representing the file extension.
6 FullName
Gets the full path of the file.
7 LastAccessTime
Gets the time the current file was last accessed.
8 LastWriteTime
Gets the time of the last written activity of the file.
9 Length
Gets the size, in bytes, of the current file.
10 Name
Gets the name of the file. 46
Contd…

Jun 21, 2024


 Commonly used methods of FileInfo class are:
S.N Method Name & Purpose
1 public StreamWriter AppendText()
Creates a StreamWriter that appends text to the file represented by this instance of the
FileInfo.
2 public FileStream Create()
Creates a file.
3 public override void Delete()
Deletes a file permanently.

Event Driven Programming


4 public void MoveTo( string destFileName )
Moves a specified file to a new location, providing the option to specify a new file name.
5 public FileStream Open( FileMode mode )
Opens a file in the specified mode.
6 public FileStream Open( FileMode mode, FileAccess access )
Opens a file in the specified mode with read, write, or read/write access.
7 public FileStream Open( FileMode mode, FileAccess access, FileShare share )
Opens a file in the specified mode with read, write, or read/write access and the
specified sharing option.
8 public FileStream OpenRead()
Creates a read-only FileStream
9 public FileStream OpenWrite()
Creates a write-only FileStream.
47
Contd…

Jun 21, 2024


 Create a FileInfo
 FileInfo object is created using the default constructor
string fileName = @"C:\Temp\MaheshTXFI.txt";
FileInfo fi = new FileInfo(fileName);
DirectoryInfo di=new DirectoryInfo(@"D:\temp");

Event Driven Programming


MessageBox.Show("***File Informations***\n “ +
“File full Name = “ + fi.FullName + “\nFile Extension
= “ + fi.Extension + “Directory Name = “
+ fi.DirectoryName + “File Size = “ + fi.Length +
“Creation Time = “ + CreationTime + “Last Access Time
= “ + fi.LastAccessTime + “Last Write Time = “
+ fi.LastWriteTime);
48
Contd…

Jun 21, 2024


 File class provides static methods for creating,
deleting, and manipulating files, whereas
 only exposes static methods & does not contain any
properties
 FileInfo class exposes instance members for files

Event Driven Programming


manipulation
 provides instance members for dealing with files. Once
you have created an instance of the FileInfo class, you
can use its members to obtain more information about a
particular file.
49
Any Question
???

Event Driven Programming Jun 21, 2024


50

You might also like