SlideShare uma empresa Scribd logo
1 de 36
Baixar para ler offline
Visual C# .Net using
framework 4.5
Eng. Mahmoud Ouf
Lecture 10
mmouf@2018
Files and Streams
Most of Files and Streams classes are defined in System.IO namespace
Many of the types within the System.IO namespace focus on the:
Programmatic manipulation of physical directories and files
(Navigating File System).
Consistent programming interface for reading and writing across a
variety of I/O types (Streams).
mmouf@2018
Navigating File System
This task includes navigating and gathering information about drives,
folders, and files.
The file system classes are separated into two types of classes:
Informational:
• expose all the system information about file system objects specifically,
files, directories, and drives.
• These classes are named FileInfo and DirectoryInfo, they inherits from
FileSystemInfo base class.
• In addition, the DriveInfo class represents a drive in the file system
Utility:
• provide static methods to perform certain operations on file system objects
such as files, directories, and file system paths.
• These utility classes include the File, Directory, and Path classes.
mmouf@2018
Navigating File System
mmouf@2018
Object
(class)
FileSystemInfo
(abstract class)
DriveInfo
(sealed class)
File
(static class)
Directory
(static class)
FileInfo
(sealed class)
DirectoryInfo
(sealed class)
Navigating File System (Informational)
FileSystemInfo class
The FileSystemInfo class provides the basic functionality for all
informational file system classes.
mmouf@2018
Properties Description
Attributes Gets or sets FileAttributes enumeration of the current file or directory.
CreationTime Gets or sets the time that the current file or directory was created
Exists Determines whether the file or directory exists. .
Extension Gets a string representation of the extension part of the file or directory
FullName Gets the full path to the file or directory
LastAccessTime Gets or sets the time the file or directory was accessed
LastWriteTime Gets or sets the time the file or directory was last written to. .
Navigating File System (Informational)
FileSystemInfo class
mmouf@2018
Properties Description
Name
Gets the simple name for the file or directory. For a file, this is the name
within the directory. For a directory, this is the last directory name in the
directory hierarchy
Methods Description
Delete Removes the file or directory from the file system .
Navigating File System (Informational)
FileInfo class
It provides the basic functionality to access and manipulate a single file in
the file system..
mmouf@2018
Properties Description
Directory
Gets the DirectoryInfo object that represents the directory that this file is
stored within.
DirectoryName Gets the name of the directory that this file is stored within
IsReadOnly Gets or sets a value that determines if the current file is read only..
Length Gets the length of the file
Navigating File System (Informational)
FileInfo class
mmouf@2018
Methods Description
AppendText Creates a new StreamWriter that will allow appending text to the file.
CopyTo Makes a copy of the file in a new location
Create Creates a file based on the current file information.
CreateText Creates a new StreamWriter and a new file for writing text
Decrypt Decrypts a file that was encrypted by the current user
Encrypt
Encrypts a file so that only the account used to encrypt the file can
decrypt it.
MoveTo Moves the file to a new location
Navigating File System (Informational)
FileInfo class
mmouf@2018
Methods Description
Open Opens the file with specific privileges (read, read/write, and so on).
OpenRead Opens the file with read-only access
OpenText
Opens the file and returns a StreamReader to allow reading of text within
the file.
OpenWrite Opens the file with write-only access
Replace Replaces a file with the information in the current FileInfo object.
Navigating File System (Informational)
DirectoryInfo class
This class contains a set of members used for creating, moving, deleting, and
enumerating over directories and subdirectories.
mmouf@2018
Properties Description
Parent
Gets the DirectoryInfo object for the parent directory of the current
directory in the directory hierarchy
Root Gets the root part of the directory’s path as a string
Navigating File System (Informational)
DirectoryInfo class
mmouf@2018
Methods Description
Create Creates the directory described in the current DirectoryInfo object
CreateSubdirect
ory
Creates a new directory as a child directory of the current directory in
the directory hierarchy
Delete Deletes a directory and all its contents
GetDirectories
Retrieves an array of DirectoryInfo objects that represent sub directories
of the current directory
GetFiles
Retrieves an array of FileInfo objects that represent all the files in the
current directory
GetFileSystemInf
os
Retrieves an array of FileSystemInfo objects that represent both files and
subdirectories in the current directory
MoveTo Moves the current directory to a new location
Navigating File System (Informational)
Begin working with the DirectoryInfo type by specifying a particular
directory path as a constructor parameter.
DirectoryInfo dir2 = new DirectoryInfo(@"C:Windows");
We use the "." notation to obtain access to the current application directory.
DirectoryInfo dir1 = new DirectoryInfo(".");
if you attempt to interact with a nonexistent directory, a
System.IO.DirectoryNotFoundException is thrown.
Thus, if you specify a directory that is not yet created, you will need to call
the Create() method before proceeding:
DirectoryInfo dir3 = new DirectoryInfo(@"C:WindowsTesting");
dir3.Create();
mmouf@2018
Navigating File System (Informational)
DriveInfo class
mmouf@2018
Properties Description
AvailableFreeSp
ace
Gets the amount of available space on the drive. The amount might be
different from the amount returned by TotalFreeSpace, depending on disk
quotas.
DriveFormat Gets the format of the drive, such as NTFS or FAT32.
IsReady Gets the status of the drive, indicating whether it is ready to be accessed..
Name Gets the name of the drive.
RootDirectory Gets a DirectoryInfo object that represents the root directory of the drive
VolumeLabel
Gets or sets the label of the drive. It might be set only on drives that are
not readonly..
TotalFreeSpace Gets the total amount of free space on the drive
Navigating File System (Informational)
DriveInfo class
The DriveType Enumeration
The DriveType enumeration provides the possible types of drives that can be
represented by a DriveInfo object.
CDRom Fixed Network Ram Removable
mmouf@2018
Properties Description
TotalSize Gets the total size of the drive
Methods Description
GetDrives A static method that returns all the drives on the current system.
DriveType Gets the type of drive in the form of the DriveType enumeration
Navigating File System (Utility)
File class
This is a static class contains a set of static Methods help in creating moving
deleting …files. Also, it has some extra methods helps when dealing with
I/O stream. There are some methods are duplicated in function with other
methods in FileInfo class, so you can use anyone of them.
mmouf@2018
Methods Description
AppendAllText
Appends a specified string into an existing file, alternatively creating the
file if it does not exist
AppendText
Opens a file (or creates a new file if one does not exist) and returns a
StreamWriter that is prepared to allow text to be appended to the file
Copy
Copies a file to a new file. The new file must not exist for Copy to be
successful..
Create Creates a new file and returns a FileStream object
Navigating File System (Utility)
File class
mmouf@2018
Methods Description
Move Moves a file from one place to another
CreateText
Creates or opens a file and returns a StreamWriter object that is ready to
have text written into it
OpenRead Opens an existing file and returns a read-only FileStream object.
OpenText Opens an existing file and returns a StreamReader object
OpenWrite Opens an existing file for writing and returns a StreamWriter object
ReadAllBytes
Opens a file, reads the contents of it into a byte array, and closes the file
in one atomic operation
ReadAllLines
Opens a file, reads the contents of it into an array of strings (one per
line), and closes the file in one atomic operation
Navigating File System (Utility)
File class
mmouf@2018
Methods Description
ReadAllText
Opens a file, reads the contents of it into a string, and closes the file in
one atomic operation.
WriteAllBytes
Opens a file, writes the contents of a byte array into it (over¬writing any
existing data), and closes the file in one atomic operation.
WriteAllLines
Opens a file, writes the contents of a string array into it (overwriting any
existing data), and closes the file in one atomic operation.
WriteAllText
Opens a file, writes the contents of a string into it (overwrit¬ing any
existing data), and closes the file in one atomic operation
Navigating File System (Utility)
Directory class
The .NET Framework supports the Directory class, which presents a
static/shared interface for manipulating and creating directories in the file
system. The Directory class provides the basic functionality to open file
streams for reading and writing.
mmouf@2018
Methods Description
CreateDirectory Creates all the directories in a supplied path
Delete Deletes a specified directory
Exists Determines whether a directory exists in the file system
GetCreationTime Returns the creation time and date of a directory
GetCurrentDirec
tory
Returns a DirectoryInfo object for the current working directory of the
application
Navigating File System (Utility)
Directory class
mmouf@2018
Methods Description
GetDirectories Gets a list of names for subdirectories in a specified directory
GetDirectoryRoo
ts
Returns the volume and/or root information for a specified directory
GetFiles Returns the names of files in a directory.
GetFileSystemEn
teries
Returns a list of subdirectories and files in the specified directory
GetLastAccessTi
me
Returns the time that a specified directory was last accessed
GetLastWriteTim
e
Returns the time that a specified directory was last written to
GetLogicalDrive
s
Gets a list of drives in the current system as strings with the pattern of
“C:”
Navigating File System (Utility)
Directory class
mmouf@2018
Methods Description
GetParent Gets the parent directory of the specified directory.
Move Moves a file or directory (and its contents) to a specified place.
SetCreationTime Sets the time a specific directory was created.
SetCurrentDirect
ory
Sets the specified directory to be the current working directory for an
application
SetLastAccessTi
me
Sets the last time a directory was accessed
SetLastWriteTim
e
Sets the last time a directory was written to
Streams (Reading / Writing files)
Stream represents a chunk of data flowing between a source and a
destination.
Streams provide a common way to interact with a sequence of bytes,
regardless of what kind of device store (e.g., file, network connection, and
printer)
The abstract Stream class defines several members that provide support for
synchronous and asynchronous interactions with the storage medium.
The Stream class is the base class for all types of streams
mmouf@2018
Streams (Reading / Writing files)
mmouf@2018
Properties Description
CanRead Determines whether the stream supports reading
CanSeek Determines whether the stream supports seeking
CanTimeOut Determines whether the stream can time out
CanWrite Determines whether the stream can be written to
Length Gets the length (in bytes) of the stream
Position
Gets or sets the virtual cursor for determining where in the stream the
current position is. The value of Position cannot be greater than the value
of the stream’s Length
ReadTimeOut Gets or sets the stream’s timeout for read operations
Stream class
Streams (Reading / Writing files)
mmouf@2018
Methods Description
Close Closes the stream and releases any resources associated with it
Flush
Clears any buffers within the stream and forces changes to be written to
the underlying system or device
Read
Performs a sequential read of a specified number of bytes from the
current position and updates the position to the end of the read upon
completion of the operation
ReadByte
Performs the read of a single byte and updates the position by moving it
by one. Identical to calling Read to read a single byte
Write
Writes information to the stream as a number of bytes and updates the
current position to reflect the new write position
WriteByte
Writes a single byte to the stream and updates the position. Identical to
calling Write with a single byte
Stream class
Streams (Reading / Writing files)
All stream classes in the .NET Framework derive from the Stream class.
These derived classes include the following:
• FileStream (System.IO)
• MemoryStream (System.IO)
• CryptoStream (System.Security)
• NetworkStream (System.Net)
• GZipStream (System.Compression)
By learning how to work with a stream in general, you can apply that
knowledge to any type of stream
mmouf@2018
Working with FileStream
The FileStream class provides an implementation for the abstract Stream members
in a manner appropriate for file-based streaming.
It is a fairly primitive stream; it can read or write only a single byte or an array of
bytes.
1. Create an object from FileStream, using the Open Method of File Class
2. As FileStream operates only on raw bytes, we need to encode the data to
corresponding byte array. System.Text namespace contains class Encoding which
contains method to encode and decode the data.
3. Write array of bytes to file using Write method of FileStream class, OR use
WriteByte in an array
4. Reset Internal Position of FileStream, set Position to 0
5. Read from File to an array of byte, use ReadByte method in a loop, OR use
Read Method
6. Decode the array of byte to original data type
mmouf@2018
Working with FileStream
class Test
{
static void Main(string[] args)
{
// Obtain a FileStream object.
FileStream fStream = File.Open(@"C:myMessage.dat",
FileMode.Create);
// Encode a string as an array of bytes.
string msg = "Hello!";
byte[] msgAsByteArray = Encoding.Default.GetBytes(msg);
// Write byte[] to file.
fStream.Write(msgAsByteArray, 0, msgAsByteArray.Length);
// Reset internal position of stream.
fStream.Position = 0;
mmouf@2018
Working with FileStream
// Read the types from file and display to console.
Console.Write("Your message as an array of bytes: ");
byte[] bytesFromFile = new byte[msgAsByteArray.Length];
for (int i = 0; i < msgAsByteArray.Length; i++)
{
bytesFromFile[i] = (byte)fStream.ReadByte();
Console.Write(bytesFromFile[i]);
}
// Display decoded messages.
Console.Write("nDecoded Message: ");
Console.WriteLine(Encoding.Default.GetString(bytesFromFile));
Console.ReadLine();
}
}
mmouf@2018
Working with Files
While the using of FileStream class is useful for writing and reading data to
files, it is a complicated process as it use the data in the raw format.
So, we need to change the data to the raw format before writing data
We need to restore the raw format to the initial form after reading data
Four classes are defined for reading and writing data.
These classes encapsulates the process of Writing data to stream and reading data
from stream in an easy manner than the classical FileStream
StreamReader and StreamWriter are used to deal with text data
BinaryReader and BinaryWriter are used to deal with binary data
mmouf@2018
Writing to a Text File:
1. Create a StreamWriter object either by:
a) Using CreateText method from File class
b) Using Create method from File, that return FileStream, and
then send this object to the constructor of the StreamWriter
2. Use the StreamWriter methods
3. Close the StreamWriter using Close method
mmouf@2018
Note: If you create the StreamWriter from available FileStream, YOU MUST
close the FileStream object after closing the StreamWriter object
Writing to a Text File:
class Test
{
public static void Main(string[] args)
{
// Get a StreamWriter and write string data.
StreamWriter writer = File.CreateText("reminders.txt")
writer.WriteLine(“Welcome to Text Files");
writer.WriteLine(“Welcome to StreamWriter");
for(int i = 0; i < 10; i++)
writer.Write(i + " ");
// Insert a new line.
writer.Write(writer.NewLine);
writer.Close();
Console.ReadLine();
}
} mmouf@2018
Reading from a Text File:
1. Create a StreamReader object either by:
a) Using OpenText method from File class
b) Using Create method from File, that return FileStream, and then
send this object to the constructor of the StreamReader
2. Use the StreamReader methods
3. Close the streamReader using Close method
mmouf@2018
Note: If you create the StreamReader from available FileStream, YOU
MUST close the FileStream object after closing the StreamReader object.
Note: If all you need to do is read out the entire file, the File class supports
reading the file in a single method call, hiding all the details of the stream and
reader implementation by calling its ReadAllText method
Console.WriteLine(File.ReadAllText(@”c:myfile.txt”));
Reading from a Text File:
class Test
{
public static void Main(string[] args)
{
// Now read data from file.
StreamReader sr = File.OpenText("reminders.txt")
string input;
while ((input = sr.ReadLine()) != null)
{
Console.WriteLine (input);
}
sr.Close();
Console.ReadLine();
}
}
mmouf@2018
Writing to a Binary File:
1. Create a BinaryWriter object by sending its constructor an object from
Stream “FileStream in case to deal with files”(this is created by using
File class methods, or FileInfo class methods)
2. Use the BinaryWriter methods
3. Close the BinaryWriter using Close method
mmouf@2018
Writing to a Binary File:
class Test
{
public static void Main(string[] args)
{
// Open a binary writer for a file.
FileInfo f = new FileInfo("BinFile.dat");
BinaryWriter bw = new BinaryWriter(f.OpenWrite());
// Create some data to save in the file
double aDouble = 1234.67;
int anInt = 34567;
string aString = "A, B, C";
// Write the data
bw.Write(aDouble);
bw.Write(anInt);
bw.Write(aString);
bw.Close();
}
} mmouf@2018
Reading from a Binary File:
1. Create a BinaryReader object by sending its constructor an object from
Stream “FileStream in case to deal with files”(this is created by using
File class methods, or FileInfo class methods)
2. Use the BinaryReader methods
3. Close the BinaryReader using Close method
mmouf@2018
Reading from a Binary File:
class Test
{
public static void Main(string[] args)
{
FileInfo f = new FileInfo("BinFile.dat");
// Read the binary data from the stream.
BinaryReader br = new BinaryReader(f.OpenRead())
Console.WriteLine(br.ReadDouble());
Console.WriteLine(br.ReadInt32());
Console.WriteLine(br.ReadString());
br.Close();
Console.ReadLine();
}
}
mmouf@2018

Mais conteúdo relacionado

Mais procurados

Ado.net &amp; data persistence frameworks
Ado.net &amp; data persistence frameworksAdo.net &amp; data persistence frameworks
Ado.net &amp; data persistence frameworks
Luis Goldster
 
Ado.net session01
Ado.net session01Ado.net session01
Ado.net session01
Niit Care
 
ADO.NET -database connection
ADO.NET -database connectionADO.NET -database connection
ADO.NET -database connection
Anekwong Yoddumnern
 
Ado.net session04
Ado.net session04Ado.net session04
Ado.net session04
Niit Care
 
Ado.net session07
Ado.net session07Ado.net session07
Ado.net session07
Niit Care
 
For Beginners - Ado.net
For Beginners - Ado.netFor Beginners - Ado.net
For Beginners - Ado.net
Tarun Jain
 

Mais procurados (20)

Ado.net &amp; data persistence frameworks
Ado.net &amp; data persistence frameworksAdo.net &amp; data persistence frameworks
Ado.net &amp; data persistence frameworks
 
ADO .Net
ADO .Net ADO .Net
ADO .Net
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
 
Ado.net
Ado.netAdo.net
Ado.net
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Ado.net
Ado.netAdo.net
Ado.net
 
Chap14 ado.net
Chap14 ado.netChap14 ado.net
Chap14 ado.net
 
Chapter 3: ado.net
Chapter 3: ado.netChapter 3: ado.net
Chapter 3: ado.net
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Ado.net session01
Ado.net session01Ado.net session01
Ado.net session01
 
2310 b 09
2310 b 092310 b 09
2310 b 09
 
ADO.NET -database connection
ADO.NET -database connectionADO.NET -database connection
ADO.NET -database connection
 
Ado.net
Ado.netAdo.net
Ado.net
 
Ado.net session04
Ado.net session04Ado.net session04
Ado.net session04
 
ADO.NET by ASP.NET Development Company in india
ADO.NET by ASP.NET  Development Company in indiaADO.NET by ASP.NET  Development Company in india
ADO.NET by ASP.NET Development Company in india
 
Ado.net session07
Ado.net session07Ado.net session07
Ado.net session07
 
Ado .net
Ado .netAdo .net
Ado .net
 
Sql ppt
Sql pptSql ppt
Sql ppt
 
ADO.NET difference faqs compiled- 1
ADO.NET difference  faqs compiled- 1ADO.NET difference  faqs compiled- 1
ADO.NET difference faqs compiled- 1
 
For Beginners - Ado.net
For Beginners - Ado.netFor Beginners - Ado.net
For Beginners - Ado.net
 

Semelhante a Intake 38 10

Ch11 OS
Ch11 OSCh11 OS
Ch11 OS
C.U
 
ASP.NET Session 7
ASP.NET Session 7ASP.NET Session 7
ASP.NET Session 7
Sisir Ghosh
 

Semelhante a Intake 38 10 (20)

Intake 37 11
Intake 37 11Intake 37 11
Intake 37 11
 
Chapter 17
Chapter 17Chapter 17
Chapter 17
 
Ch10
Ch10Ch10
Ch10
 
file management_osnotes.ppt
file management_osnotes.pptfile management_osnotes.ppt
file management_osnotes.ppt
 
Chapter 10 - File System Interface
Chapter 10 - File System InterfaceChapter 10 - File System Interface
Chapter 10 - File System Interface
 
File Systems
File SystemsFile Systems
File Systems
 
Ch11 OS
Ch11 OSCh11 OS
Ch11 OS
 
OSCh11
OSCh11OSCh11
OSCh11
 
OS_Ch11
OS_Ch11OS_Ch11
OS_Ch11
 
Chapter 12.pptx
Chapter 12.pptxChapter 12.pptx
Chapter 12.pptx
 
ASP.NET Session 7
ASP.NET Session 7ASP.NET Session 7
ASP.NET Session 7
 
File system interfacefinal
File system interfacefinalFile system interfacefinal
File system interfacefinal
 
Switching & Multiplexing
Switching & MultiplexingSwitching & Multiplexing
Switching & Multiplexing
 
File systeminterface-pre-final-formatting
File systeminterface-pre-final-formattingFile systeminterface-pre-final-formatting
File systeminterface-pre-final-formatting
 
File system interface Pre Final
File system interface Pre FinalFile system interface Pre Final
File system interface Pre Final
 
Unit ivos - file systems
Unit ivos - file systemsUnit ivos - file systems
Unit ivos - file systems
 
History
HistoryHistory
History
 
Learn about the File Concept in operating systems ppt
Learn about the File Concept in operating systems pptLearn about the File Concept in operating systems ppt
Learn about the File Concept in operating systems ppt
 
File System in Operating System
File System in Operating SystemFile System in Operating System
File System in Operating System
 
Directory structure
Directory structureDirectory structure
Directory structure
 

Mais de Mahmoud Ouf (20)

Relation between classes in arabic
Relation between classes in arabicRelation between classes in arabic
Relation between classes in arabic
 
Intake 38 data access 5
Intake 38 data access 5Intake 38 data access 5
Intake 38 data access 5
 
Intake 38 data access 3
Intake 38 data access 3Intake 38 data access 3
Intake 38 data access 3
 
Intake 38 12
Intake 38 12Intake 38 12
Intake 38 12
 
Intake 38 11
Intake 38 11Intake 38 11
Intake 38 11
 
Intake 38 9
Intake 38 9Intake 38 9
Intake 38 9
 
Intake 38 8
Intake 38 8Intake 38 8
Intake 38 8
 
Intake 38 7
Intake 38 7Intake 38 7
Intake 38 7
 
Intake 38 6
Intake 38 6Intake 38 6
Intake 38 6
 
Intake 38 5 1
Intake 38 5 1Intake 38 5 1
Intake 38 5 1
 
Intake 38 5
Intake 38 5Intake 38 5
Intake 38 5
 
Intake 38 4
Intake 38 4Intake 38 4
Intake 38 4
 
Intake 38 3
Intake 38 3Intake 38 3
Intake 38 3
 
Intake 38 2
Intake 38 2Intake 38 2
Intake 38 2
 
Intake 38_1
Intake 38_1Intake 38_1
Intake 38_1
 
Intake 37 DM
Intake 37 DMIntake 37 DM
Intake 37 DM
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
Intake 37 ef1
Intake 37 ef1Intake 37 ef1
Intake 37 ef1
 
Intake 37 linq3
Intake 37 linq3Intake 37 linq3
Intake 37 linq3
 
Intake 37 linq2
Intake 37 linq2Intake 37 linq2
Intake 37 linq2
 

Último

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Último (20)

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 

Intake 38 10

  • 1. Visual C# .Net using framework 4.5 Eng. Mahmoud Ouf Lecture 10 mmouf@2018
  • 2. Files and Streams Most of Files and Streams classes are defined in System.IO namespace Many of the types within the System.IO namespace focus on the: Programmatic manipulation of physical directories and files (Navigating File System). Consistent programming interface for reading and writing across a variety of I/O types (Streams). mmouf@2018
  • 3. Navigating File System This task includes navigating and gathering information about drives, folders, and files. The file system classes are separated into two types of classes: Informational: • expose all the system information about file system objects specifically, files, directories, and drives. • These classes are named FileInfo and DirectoryInfo, they inherits from FileSystemInfo base class. • In addition, the DriveInfo class represents a drive in the file system Utility: • provide static methods to perform certain operations on file system objects such as files, directories, and file system paths. • These utility classes include the File, Directory, and Path classes. mmouf@2018
  • 4. Navigating File System mmouf@2018 Object (class) FileSystemInfo (abstract class) DriveInfo (sealed class) File (static class) Directory (static class) FileInfo (sealed class) DirectoryInfo (sealed class)
  • 5. Navigating File System (Informational) FileSystemInfo class The FileSystemInfo class provides the basic functionality for all informational file system classes. mmouf@2018 Properties Description Attributes Gets or sets FileAttributes enumeration of the current file or directory. CreationTime Gets or sets the time that the current file or directory was created Exists Determines whether the file or directory exists. . Extension Gets a string representation of the extension part of the file or directory FullName Gets the full path to the file or directory LastAccessTime Gets or sets the time the file or directory was accessed LastWriteTime Gets or sets the time the file or directory was last written to. .
  • 6. Navigating File System (Informational) FileSystemInfo class mmouf@2018 Properties Description Name Gets the simple name for the file or directory. For a file, this is the name within the directory. For a directory, this is the last directory name in the directory hierarchy Methods Description Delete Removes the file or directory from the file system .
  • 7. Navigating File System (Informational) FileInfo class It provides the basic functionality to access and manipulate a single file in the file system.. mmouf@2018 Properties Description Directory Gets the DirectoryInfo object that represents the directory that this file is stored within. DirectoryName Gets the name of the directory that this file is stored within IsReadOnly Gets or sets a value that determines if the current file is read only.. Length Gets the length of the file
  • 8. Navigating File System (Informational) FileInfo class mmouf@2018 Methods Description AppendText Creates a new StreamWriter that will allow appending text to the file. CopyTo Makes a copy of the file in a new location Create Creates a file based on the current file information. CreateText Creates a new StreamWriter and a new file for writing text Decrypt Decrypts a file that was encrypted by the current user Encrypt Encrypts a file so that only the account used to encrypt the file can decrypt it. MoveTo Moves the file to a new location
  • 9. Navigating File System (Informational) FileInfo class mmouf@2018 Methods Description Open Opens the file with specific privileges (read, read/write, and so on). OpenRead Opens the file with read-only access OpenText Opens the file and returns a StreamReader to allow reading of text within the file. OpenWrite Opens the file with write-only access Replace Replaces a file with the information in the current FileInfo object.
  • 10. Navigating File System (Informational) DirectoryInfo class This class contains a set of members used for creating, moving, deleting, and enumerating over directories and subdirectories. mmouf@2018 Properties Description Parent Gets the DirectoryInfo object for the parent directory of the current directory in the directory hierarchy Root Gets the root part of the directory’s path as a string
  • 11. Navigating File System (Informational) DirectoryInfo class mmouf@2018 Methods Description Create Creates the directory described in the current DirectoryInfo object CreateSubdirect ory Creates a new directory as a child directory of the current directory in the directory hierarchy Delete Deletes a directory and all its contents GetDirectories Retrieves an array of DirectoryInfo objects that represent sub directories of the current directory GetFiles Retrieves an array of FileInfo objects that represent all the files in the current directory GetFileSystemInf os Retrieves an array of FileSystemInfo objects that represent both files and subdirectories in the current directory MoveTo Moves the current directory to a new location
  • 12. Navigating File System (Informational) Begin working with the DirectoryInfo type by specifying a particular directory path as a constructor parameter. DirectoryInfo dir2 = new DirectoryInfo(@"C:Windows"); We use the "." notation to obtain access to the current application directory. DirectoryInfo dir1 = new DirectoryInfo("."); if you attempt to interact with a nonexistent directory, a System.IO.DirectoryNotFoundException is thrown. Thus, if you specify a directory that is not yet created, you will need to call the Create() method before proceeding: DirectoryInfo dir3 = new DirectoryInfo(@"C:WindowsTesting"); dir3.Create(); mmouf@2018
  • 13. Navigating File System (Informational) DriveInfo class mmouf@2018 Properties Description AvailableFreeSp ace Gets the amount of available space on the drive. The amount might be different from the amount returned by TotalFreeSpace, depending on disk quotas. DriveFormat Gets the format of the drive, such as NTFS or FAT32. IsReady Gets the status of the drive, indicating whether it is ready to be accessed.. Name Gets the name of the drive. RootDirectory Gets a DirectoryInfo object that represents the root directory of the drive VolumeLabel Gets or sets the label of the drive. It might be set only on drives that are not readonly.. TotalFreeSpace Gets the total amount of free space on the drive
  • 14. Navigating File System (Informational) DriveInfo class The DriveType Enumeration The DriveType enumeration provides the possible types of drives that can be represented by a DriveInfo object. CDRom Fixed Network Ram Removable mmouf@2018 Properties Description TotalSize Gets the total size of the drive Methods Description GetDrives A static method that returns all the drives on the current system. DriveType Gets the type of drive in the form of the DriveType enumeration
  • 15. Navigating File System (Utility) File class This is a static class contains a set of static Methods help in creating moving deleting …files. Also, it has some extra methods helps when dealing with I/O stream. There are some methods are duplicated in function with other methods in FileInfo class, so you can use anyone of them. mmouf@2018 Methods Description AppendAllText Appends a specified string into an existing file, alternatively creating the file if it does not exist AppendText Opens a file (or creates a new file if one does not exist) and returns a StreamWriter that is prepared to allow text to be appended to the file Copy Copies a file to a new file. The new file must not exist for Copy to be successful.. Create Creates a new file and returns a FileStream object
  • 16. Navigating File System (Utility) File class mmouf@2018 Methods Description Move Moves a file from one place to another CreateText Creates or opens a file and returns a StreamWriter object that is ready to have text written into it OpenRead Opens an existing file and returns a read-only FileStream object. OpenText Opens an existing file and returns a StreamReader object OpenWrite Opens an existing file for writing and returns a StreamWriter object ReadAllBytes Opens a file, reads the contents of it into a byte array, and closes the file in one atomic operation ReadAllLines Opens a file, reads the contents of it into an array of strings (one per line), and closes the file in one atomic operation
  • 17. Navigating File System (Utility) File class mmouf@2018 Methods Description ReadAllText Opens a file, reads the contents of it into a string, and closes the file in one atomic operation. WriteAllBytes Opens a file, writes the contents of a byte array into it (over¬writing any existing data), and closes the file in one atomic operation. WriteAllLines Opens a file, writes the contents of a string array into it (overwriting any existing data), and closes the file in one atomic operation. WriteAllText Opens a file, writes the contents of a string into it (overwrit¬ing any existing data), and closes the file in one atomic operation
  • 18. Navigating File System (Utility) Directory class The .NET Framework supports the Directory class, which presents a static/shared interface for manipulating and creating directories in the file system. The Directory class provides the basic functionality to open file streams for reading and writing. mmouf@2018 Methods Description CreateDirectory Creates all the directories in a supplied path Delete Deletes a specified directory Exists Determines whether a directory exists in the file system GetCreationTime Returns the creation time and date of a directory GetCurrentDirec tory Returns a DirectoryInfo object for the current working directory of the application
  • 19. Navigating File System (Utility) Directory class mmouf@2018 Methods Description GetDirectories Gets a list of names for subdirectories in a specified directory GetDirectoryRoo ts Returns the volume and/or root information for a specified directory GetFiles Returns the names of files in a directory. GetFileSystemEn teries Returns a list of subdirectories and files in the specified directory GetLastAccessTi me Returns the time that a specified directory was last accessed GetLastWriteTim e Returns the time that a specified directory was last written to GetLogicalDrive s Gets a list of drives in the current system as strings with the pattern of “C:”
  • 20. Navigating File System (Utility) Directory class mmouf@2018 Methods Description GetParent Gets the parent directory of the specified directory. Move Moves a file or directory (and its contents) to a specified place. SetCreationTime Sets the time a specific directory was created. SetCurrentDirect ory Sets the specified directory to be the current working directory for an application SetLastAccessTi me Sets the last time a directory was accessed SetLastWriteTim e Sets the last time a directory was written to
  • 21. Streams (Reading / Writing files) Stream represents a chunk of data flowing between a source and a destination. Streams provide a common way to interact with a sequence of bytes, regardless of what kind of device store (e.g., file, network connection, and printer) The abstract Stream class defines several members that provide support for synchronous and asynchronous interactions with the storage medium. The Stream class is the base class for all types of streams mmouf@2018
  • 22. Streams (Reading / Writing files) mmouf@2018 Properties Description CanRead Determines whether the stream supports reading CanSeek Determines whether the stream supports seeking CanTimeOut Determines whether the stream can time out CanWrite Determines whether the stream can be written to Length Gets the length (in bytes) of the stream Position Gets or sets the virtual cursor for determining where in the stream the current position is. The value of Position cannot be greater than the value of the stream’s Length ReadTimeOut Gets or sets the stream’s timeout for read operations Stream class
  • 23. Streams (Reading / Writing files) mmouf@2018 Methods Description Close Closes the stream and releases any resources associated with it Flush Clears any buffers within the stream and forces changes to be written to the underlying system or device Read Performs a sequential read of a specified number of bytes from the current position and updates the position to the end of the read upon completion of the operation ReadByte Performs the read of a single byte and updates the position by moving it by one. Identical to calling Read to read a single byte Write Writes information to the stream as a number of bytes and updates the current position to reflect the new write position WriteByte Writes a single byte to the stream and updates the position. Identical to calling Write with a single byte Stream class
  • 24. Streams (Reading / Writing files) All stream classes in the .NET Framework derive from the Stream class. These derived classes include the following: • FileStream (System.IO) • MemoryStream (System.IO) • CryptoStream (System.Security) • NetworkStream (System.Net) • GZipStream (System.Compression) By learning how to work with a stream in general, you can apply that knowledge to any type of stream mmouf@2018
  • 25. Working with FileStream The FileStream class provides an implementation for the abstract Stream members in a manner appropriate for file-based streaming. It is a fairly primitive stream; it can read or write only a single byte or an array of bytes. 1. Create an object from FileStream, using the Open Method of File Class 2. As FileStream operates only on raw bytes, we need to encode the data to corresponding byte array. System.Text namespace contains class Encoding which contains method to encode and decode the data. 3. Write array of bytes to file using Write method of FileStream class, OR use WriteByte in an array 4. Reset Internal Position of FileStream, set Position to 0 5. Read from File to an array of byte, use ReadByte method in a loop, OR use Read Method 6. Decode the array of byte to original data type mmouf@2018
  • 26. Working with FileStream class Test { static void Main(string[] args) { // Obtain a FileStream object. FileStream fStream = File.Open(@"C:myMessage.dat", FileMode.Create); // Encode a string as an array of bytes. string msg = "Hello!"; byte[] msgAsByteArray = Encoding.Default.GetBytes(msg); // Write byte[] to file. fStream.Write(msgAsByteArray, 0, msgAsByteArray.Length); // Reset internal position of stream. fStream.Position = 0; mmouf@2018
  • 27. Working with FileStream // Read the types from file and display to console. Console.Write("Your message as an array of bytes: "); byte[] bytesFromFile = new byte[msgAsByteArray.Length]; for (int i = 0; i < msgAsByteArray.Length; i++) { bytesFromFile[i] = (byte)fStream.ReadByte(); Console.Write(bytesFromFile[i]); } // Display decoded messages. Console.Write("nDecoded Message: "); Console.WriteLine(Encoding.Default.GetString(bytesFromFile)); Console.ReadLine(); } } mmouf@2018
  • 28. Working with Files While the using of FileStream class is useful for writing and reading data to files, it is a complicated process as it use the data in the raw format. So, we need to change the data to the raw format before writing data We need to restore the raw format to the initial form after reading data Four classes are defined for reading and writing data. These classes encapsulates the process of Writing data to stream and reading data from stream in an easy manner than the classical FileStream StreamReader and StreamWriter are used to deal with text data BinaryReader and BinaryWriter are used to deal with binary data mmouf@2018
  • 29. Writing to a Text File: 1. Create a StreamWriter object either by: a) Using CreateText method from File class b) Using Create method from File, that return FileStream, and then send this object to the constructor of the StreamWriter 2. Use the StreamWriter methods 3. Close the StreamWriter using Close method mmouf@2018 Note: If you create the StreamWriter from available FileStream, YOU MUST close the FileStream object after closing the StreamWriter object
  • 30. Writing to a Text File: class Test { public static void Main(string[] args) { // Get a StreamWriter and write string data. StreamWriter writer = File.CreateText("reminders.txt") writer.WriteLine(“Welcome to Text Files"); writer.WriteLine(“Welcome to StreamWriter"); for(int i = 0; i < 10; i++) writer.Write(i + " "); // Insert a new line. writer.Write(writer.NewLine); writer.Close(); Console.ReadLine(); } } mmouf@2018
  • 31. Reading from a Text File: 1. Create a StreamReader object either by: a) Using OpenText method from File class b) Using Create method from File, that return FileStream, and then send this object to the constructor of the StreamReader 2. Use the StreamReader methods 3. Close the streamReader using Close method mmouf@2018 Note: If you create the StreamReader from available FileStream, YOU MUST close the FileStream object after closing the StreamReader object. Note: If all you need to do is read out the entire file, the File class supports reading the file in a single method call, hiding all the details of the stream and reader implementation by calling its ReadAllText method Console.WriteLine(File.ReadAllText(@”c:myfile.txt”));
  • 32. Reading from a Text File: class Test { public static void Main(string[] args) { // Now read data from file. StreamReader sr = File.OpenText("reminders.txt") string input; while ((input = sr.ReadLine()) != null) { Console.WriteLine (input); } sr.Close(); Console.ReadLine(); } } mmouf@2018
  • 33. Writing to a Binary File: 1. Create a BinaryWriter object by sending its constructor an object from Stream “FileStream in case to deal with files”(this is created by using File class methods, or FileInfo class methods) 2. Use the BinaryWriter methods 3. Close the BinaryWriter using Close method mmouf@2018
  • 34. Writing to a Binary File: class Test { public static void Main(string[] args) { // Open a binary writer for a file. FileInfo f = new FileInfo("BinFile.dat"); BinaryWriter bw = new BinaryWriter(f.OpenWrite()); // Create some data to save in the file double aDouble = 1234.67; int anInt = 34567; string aString = "A, B, C"; // Write the data bw.Write(aDouble); bw.Write(anInt); bw.Write(aString); bw.Close(); } } mmouf@2018
  • 35. Reading from a Binary File: 1. Create a BinaryReader object by sending its constructor an object from Stream “FileStream in case to deal with files”(this is created by using File class methods, or FileInfo class methods) 2. Use the BinaryReader methods 3. Close the BinaryReader using Close method mmouf@2018
  • 36. Reading from a Binary File: class Test { public static void Main(string[] args) { FileInfo f = new FileInfo("BinFile.dat"); // Read the binary data from the stream. BinaryReader br = new BinaryReader(f.OpenRead()) Console.WriteLine(br.ReadDouble()); Console.WriteLine(br.ReadInt32()); Console.WriteLine(br.ReadString()); br.Close(); Console.ReadLine(); } } mmouf@2018