SlideShare une entreprise Scribd logo
1  sur  42
File Types, Using Streams and Manipulating Files
Streams, Files and Directories
Software University
http://softuni.bg
SoftUni Team
Technical Trainers
1. What are Streams?
2. Readers and Writers
3. File Streams
4. File Class
5. Directory Class
Table of Contents
2
sli.do
#fund-csharp
Have a Question?
3
What Is a Stream?
Basic Concepts
 Streams are used to transfer data
 We open a stream to:
 Read data
 Write data
What is a Stream?
5
1100 1001 1001
Stream
 Streams are means for transferring (reading and writing) data
 Streams are ordered sequences of bytes
 Provide sequential access to its elements
 Different types of streams are available to
access different data sources:
 File access, network access, memory streams and others
 Streams are opened before using them and closed after that
Stream Basics
6
 Position is the current position in the stream
 Buffer keeps n bytes of the stream from the current position
Stream – Example
7
F i l e s a n d
46 69 6c 65 73 20 61 6e 64
Length = 9
Position
46 69Buffer 6c 65 73 20 61 6e 64
Stream Types in .NET
8
Readers and Writers
Text and Binary Readers/Writers
 Readers and writers are classes, which facilitate the work
with streams
 Two types of streams
 Text readers/writers – StreamReader / StreamWriter
 Provide methods ReadLine(), WriteLine()
(similar to working with the system class Console)
 Binary readers/writers – BinaryReader / BinaryWriter
 Provide methods for working with primitive types
 ReadInt32(), ReadBoolean(), WriteChar(), etc.
Readers and Writers
10
 Streams, readers, files, etc. use certain resources
 Using statement closes them and releases their
resources
Using statement
11
var reader = new StreamReader(fileName);
using (reader)
{
// Use the reader here
}
 Read the content from your Input.txt file
 Print the odd lines on the console
 Counting starts from 0
Problem: Odd Lines
12
Two households, both alike in dignity,
In fair Verona, where we lay our scene,
From ancient grudge break to new mutiny,
Where civil blood makes civil hands unclean.
In fair Verona, where we lay our scene,
Where civil blood makes civil hands unclean.
Solution: Odd Lines
13
var reader = new StreamReader("Input.txt");
using (reader){
int counter = 0;
string line = reader.ReadLine();
using (var writer = new StreamWriter("Output.txt")){
while (line != null){
if (counter % 2 == 1){
writer.WriteLine(line);}
counter++;
line = reader.ReadLine();}}}
 Read your Input.txt file
 Insert a number in front of each line of the file
 Save it in Output.txt
Problem: Line Numbers
14
Two households, both alike in dignity,
In fair Verona, where we lay our scene,
From ancient grudge break to new mutiny,
Where civil blood makes civil hands unclean.
1. Two households, both alike in dignity,
2. In fair Verona, where we lay our scene,
3. From ancient grudge break to new mutiny,
4. Where civil blood makes civil hands unclean.
Solution: Line Numbers
15
using (var reader = new StreamReader("Input.txt"))
{
string line = reader.ReadLine();
int counter = 1;
using (var writer = new StreamWriter("Output.txt"))
{
while (line != null)
{
writer.WriteLine($"{counter}. {line}");
line = reader.ReadLine();
counter++;
}
}
}
Base Streams
 The base class for all streams is System.IO.Stream
 There are defined methods for
the main operations with streams in it
 Some streams do not support read, write
or positioning operations
 Properties CanRead, CanWrite and CanSeek are provided
 Streams which support positioning
have the properties Position and Length
The System.IO.Stream Class
17
 int Read(byte[] buffer, int offset, int count)
 Read as many as count bytes from input stream,
starting from the given offset position
 Returns the number of read bytes or 0
if end of stream is reached
 Can freeze for undefined time while reading at least 1 byte
 Can read less than the claimed number of bytes
Methods of System.IO.Stream Class
18
F i l e s a n d
46 69 6c 65 73 20 61 6e 64
 Write(byte[] buffer, int offset, int count)
 Writes a sequence of count bytes to an output stream,
starting from the given offset position
 Can freeze for undefined time,
until it sends all bytes to their destination
 Flush()
 Sends the internal buffers data to its destination
(data storage, I/O device, etc.)
Methods of System.IO.Stream Class (2)
19
 Close()
 Calls Flush()
 Closes the connection to the device (mechanism)
 Releases the used resources
 Seek(offset, SeekOrigin)
 Moves the position (if supported) with given offset
towards the beginning, the end or the current position
Methods of System.IO.Stream Class (3)
20
File Stream
 Inherits the Stream class and supports all its methods
and properties
 Supports reading, writing, positioning operations, etc.
 The constructor contains parameters for:
 File name
 File open mode
 File access mode
 Concurrent users access mode
The FileStream Class
22
 FileMode – opening file mode
 Open, Append, Create,
CreateNew, OpenOrCreate, Truncate
 FileAccess – operations mode for the file
 Read, Write, ReadWrite
 FileShare – access rules for other users while file is opened
 None, Read, Write, ReadWrite
The FileStream Class (2)
23
Optional parameters
var fs = new FileStream(string fileName, FileMode,
[FileAccess], [FileShare]);
Writing Text to File – Example
24
string text = "Кирилица";
var fileStream = new FileStream("../../log.txt",
FileMode.Create);
try {
byte[] bytes = Encoding.UTF8.GetBytes(text);
fileStream.Write(bytes, 0, bytes.Length);
}
finally
{ fileStream.Close(); }
try-finally guarantees the
stream will always close
Encoding.UTF8.GetBytes() returns
the underlying bytes of the character
 Slice the file sliceMe.txt in 4 equal parts
 Name them
 Part-1.txt
 Part-2.txt
 Part-3.txt
 Part-4.txt
Problem: Slice File
25
Solution: Slice File
26
string destinationDirectory = ""; //Add saving path
string sourceFile = ""; //Add file path
int parts = 4;
List<string> files = new List<string> { "Part-1.txt", "Part-
2.txt ", "Part-3.txt ", "Part-4.txt" };
using (var streamReadFile = new FileStream(sourceFile,
FileMode.Open)){
long pieceSize =
(long)Math.Ceiling((double)streamReadFile.Length /
parts);
for (int i = 0; i < parts; i++){
long currentPieceSize = 0;
//Continue to next slide
}}
Solution: Slice File(2)
27
using (var streamCreateFile = new FileStream(files[i],
FileMode.Create)){
byte[] buffer = new byte[4096];
while ((streamReadFile.Read(buffer, 0,
buffer.Length)) == buffer.Length){
currentPieceSize += buffer.Length;
streamCreateFile.Write(buffer, 0,
buffer.Length);
if (currentPieceSize >= pieceSize){break;}
}
}
File Class in .NET
.NET API for Easily Working with Files
 File.ReadAllText()  string – reads a text file at once
 File.ReadAllLines()  string[] – reads a text file's lines
Reading Text Files
29
using System.IO;
…
string text = File.ReadAllText("file.txt");
using System.IO;
…
string[] lines = File.ReadAllLines("file.txt");
 Writing a string to a text file:
 Writing a sequence of strings to a text file, at separate lines:
 Appending additional text to an existing file:
Writing Text Files
30
string[] names = { "peter", "irina", "george", "maria" };
File.WriteAllLines("output.txt", names);
File.WriteAllText("output.txt", "Files are fun :)");
File.AppendAllText("output.txt", "nMore textn");
Directory Class in .NET
.NET API for Working with Directories
 Creating a directory (with all its subdirectories at the specified
path), unless they already exists:
 Deleting a directory (with its contents):
 Moving a file or a directory to a new location:
Basic Directory Operations
32
Directory.CreateDirectory("TestFolder");
Directory.Delete("TestFolder", true);
Directory.Move("Test", "New Folder");
 GetFiles() – returns the names of the files (including their
paths) in the specified directory
 GetDirectories() – returns the names of the subdirectories
(including their paths) in the specified directory
Listing Directory Contents
33
string[] filesInDir =
Directory.GetFiles("TestFolder");
string[] subDirs =
Directory.GetDirectories("TestFolder");
 You are given a folder named TestFolder
 Calculate the size of all files in the folder (without subfolders)
 Print the result in a file "output.txt" in Megabytes
Problem: Calculate Folder Size
34
output.txt
5.16173839569092
Solution: Calculate Folder Size
35
string[] files = Directory.GetFiles("TestFolder");
double sum = 0;
foreach (string file in files)
{
FileInfo fileInfo = new FileInfo(file);
sum += fileInfo.Length;
}
sum = sum / 1024 / 1024;
File.WriteAllText("оutput.txt", sum.ToString());
Live Exercises
 …
 …
 …
Summary
37
 Streams are ordered sequences of bytes
 Serve as I/O mechanisms
 Can be read or written to (or both)
 Always close streams by using
try-finally or using(…)
 Use the File class to work with files
 Use the Directory class to work with
directories
 https://softuni.bg/trainings/courses
SoftUni Diamond Partners
SoftUni Organizational Partners
 Software University – High-Quality Education and
Employment Opportunities
 softuni.bg
 Software University Foundation
 http://softuni.foundation/
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg
Trainings @ Software University (SoftUni)
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCom
mercial-ShareAlike 4.0 International" license
License
42

Contenu connexe

Tendances

02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variablesIntro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Svetlin Nakov
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionSvetlin Nakov
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingSvetlin Nakov
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Pedro Rodrigues
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)Pedro Rodrigues
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Pedro Rodrigues
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling Intro C# Book
 
Python language data types
Python language data typesPython language data types
Python language data typesHoang Nguyen
 

Tendances (20)

02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
06.Loops
06.Loops06.Loops
06.Loops
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
 
09. Methods
09. Methods09. Methods
09. Methods
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text Processing
 
Java introduction
Java introductionJava introduction
Java introduction
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
 
DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)
 
Ruby Programming Assignment Help
Ruby Programming Assignment HelpRuby Programming Assignment Help
Ruby Programming Assignment Help
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Chapter 2 Java Methods
Chapter 2 Java MethodsChapter 2 Java Methods
Chapter 2 Java Methods
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
Python language data types
Python language data typesPython language data types
Python language data types
 
Java generics
Java genericsJava generics
Java generics
 

Similaire à 15. Streams Files and Directories

Similaire à 15. Streams Files and Directories (20)

Data file handling
Data file handlingData file handling
Data file handling
 
15. text files
15. text files15. text files
15. text files
 
IOStream.pptx
IOStream.pptxIOStream.pptx
IOStream.pptx
 
Input/Output Exploring java.io
Input/Output Exploring java.ioInput/Output Exploring java.io
Input/Output Exploring java.io
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
file handling c++
file handling c++file handling c++
file handling c++
 
ASP.NET Session 7
ASP.NET Session 7ASP.NET Session 7
ASP.NET Session 7
 
File Input and output.pptx
File Input  and output.pptxFile Input  and output.pptx
File Input and output.pptx
 
Filehandlinging cp2
Filehandlinging cp2Filehandlinging cp2
Filehandlinging cp2
 
CSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdfCSE3146-ADV JAVA M2.pdf
CSE3146-ADV JAVA M2.pdf
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
Io Streams
Io StreamsIo Streams
Io Streams
 
Java 7 Features and Enhancements
Java 7 Features and EnhancementsJava 7 Features and Enhancements
Java 7 Features and Enhancements
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handling
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handling
 
Files nts
Files ntsFiles nts
Files nts
 
File Handling in C++
File Handling in C++File Handling in C++
File Handling in C++
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 

Plus de Intro C# Book

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversalIntro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming CodeIntro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism Intro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classesIntro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem SolvingIntro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQIntro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming CodeIntro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and SetIntro C# Book
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like StructuresIntro C# Book
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro C# Book
 

Plus de Intro C# Book (19)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 

Dernier

VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girladitipandeya
 
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableSeo
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...Neha Pandey
 
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024APNIC
 
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...Delhi Call girls
 
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.soniya singh
 
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.soniya singh
 
On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024APNIC
 
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceDelhi Call girls
 
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Callshivangimorya083
 
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...Diya Sharma
 
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Networking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOGNetworking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOGAPNIC
 
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Call Girls in Nagpur High Profile
 
(+971568250507 ))# Young Call Girls in Ajman By Pakistani Call Girls in ...
(+971568250507  ))#  Young Call Girls  in Ajman  By Pakistani Call Girls  in ...(+971568250507  ))#  Young Call Girls  in Ajman  By Pakistani Call Girls  in ...
(+971568250507 ))# Young Call Girls in Ajman By Pakistani Call Girls in ...Escorts Call Girls
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)Delhi Call girls
 
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...SofiyaSharma5
 

Dernier (20)

VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
 
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service AvailableCall Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
Call Girls Ludhiana Just Call 98765-12871 Top Class Call Girl Service Available
 
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
𓀤Call On 7877925207 𓀤 Ahmedguda Call Girls Hot Model With Sexy Bhabi Ready Fo...
 
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
 
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
Hire↠Young Call Girls in Tilak nagar (Delhi) ☎️ 9205541914 ☎️ Independent Esc...
 
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Green Park Escort Service Delhi N.C.R.
 
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
 
On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024
 
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
 
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip CallDelhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
Delhi Call Girls Rohini 9711199171 ☎✔👌✔ Whatsapp Hard And Sexy Vip Call
 
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
 
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 26 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Pratap Nagar Delhi 💯Call Us 🔝8264348440🔝
 
Networking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOGNetworking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOG
 
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
VVVIP Call Girls In Connaught Place ➡️ Delhi ➡️ 9999965857 🚀 No Advance 24HRS...
 
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...Top Rated  Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
Top Rated Pune Call Girls Daund ⟟ 6297143586 ⟟ Call Me For Genuine Sex Servi...
 
(+971568250507 ))# Young Call Girls in Ajman By Pakistani Call Girls in ...
(+971568250507  ))#  Young Call Girls  in Ajman  By Pakistani Call Girls  in ...(+971568250507  ))#  Young Call Girls  in Ajman  By Pakistani Call Girls  in ...
(+971568250507 ))# Young Call Girls in Ajman By Pakistani Call Girls in ...
 
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
WhatsApp 📞 8448380779 ✅Call Girls In Mamura Sector 66 ( Noida)
 
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
 

15. Streams Files and Directories

  • 1. File Types, Using Streams and Manipulating Files Streams, Files and Directories Software University http://softuni.bg SoftUni Team Technical Trainers
  • 2. 1. What are Streams? 2. Readers and Writers 3. File Streams 4. File Class 5. Directory Class Table of Contents 2
  • 4. What Is a Stream? Basic Concepts
  • 5.  Streams are used to transfer data  We open a stream to:  Read data  Write data What is a Stream? 5 1100 1001 1001 Stream
  • 6.  Streams are means for transferring (reading and writing) data  Streams are ordered sequences of bytes  Provide sequential access to its elements  Different types of streams are available to access different data sources:  File access, network access, memory streams and others  Streams are opened before using them and closed after that Stream Basics 6
  • 7.  Position is the current position in the stream  Buffer keeps n bytes of the stream from the current position Stream – Example 7 F i l e s a n d 46 69 6c 65 73 20 61 6e 64 Length = 9 Position 46 69Buffer 6c 65 73 20 61 6e 64
  • 9. Readers and Writers Text and Binary Readers/Writers
  • 10.  Readers and writers are classes, which facilitate the work with streams  Two types of streams  Text readers/writers – StreamReader / StreamWriter  Provide methods ReadLine(), WriteLine() (similar to working with the system class Console)  Binary readers/writers – BinaryReader / BinaryWriter  Provide methods for working with primitive types  ReadInt32(), ReadBoolean(), WriteChar(), etc. Readers and Writers 10
  • 11.  Streams, readers, files, etc. use certain resources  Using statement closes them and releases their resources Using statement 11 var reader = new StreamReader(fileName); using (reader) { // Use the reader here }
  • 12.  Read the content from your Input.txt file  Print the odd lines on the console  Counting starts from 0 Problem: Odd Lines 12 Two households, both alike in dignity, In fair Verona, where we lay our scene, From ancient grudge break to new mutiny, Where civil blood makes civil hands unclean. In fair Verona, where we lay our scene, Where civil blood makes civil hands unclean.
  • 13. Solution: Odd Lines 13 var reader = new StreamReader("Input.txt"); using (reader){ int counter = 0; string line = reader.ReadLine(); using (var writer = new StreamWriter("Output.txt")){ while (line != null){ if (counter % 2 == 1){ writer.WriteLine(line);} counter++; line = reader.ReadLine();}}}
  • 14.  Read your Input.txt file  Insert a number in front of each line of the file  Save it in Output.txt Problem: Line Numbers 14 Two households, both alike in dignity, In fair Verona, where we lay our scene, From ancient grudge break to new mutiny, Where civil blood makes civil hands unclean. 1. Two households, both alike in dignity, 2. In fair Verona, where we lay our scene, 3. From ancient grudge break to new mutiny, 4. Where civil blood makes civil hands unclean.
  • 15. Solution: Line Numbers 15 using (var reader = new StreamReader("Input.txt")) { string line = reader.ReadLine(); int counter = 1; using (var writer = new StreamWriter("Output.txt")) { while (line != null) { writer.WriteLine($"{counter}. {line}"); line = reader.ReadLine(); counter++; } } }
  • 17.  The base class for all streams is System.IO.Stream  There are defined methods for the main operations with streams in it  Some streams do not support read, write or positioning operations  Properties CanRead, CanWrite and CanSeek are provided  Streams which support positioning have the properties Position and Length The System.IO.Stream Class 17
  • 18.  int Read(byte[] buffer, int offset, int count)  Read as many as count bytes from input stream, starting from the given offset position  Returns the number of read bytes or 0 if end of stream is reached  Can freeze for undefined time while reading at least 1 byte  Can read less than the claimed number of bytes Methods of System.IO.Stream Class 18 F i l e s a n d 46 69 6c 65 73 20 61 6e 64
  • 19.  Write(byte[] buffer, int offset, int count)  Writes a sequence of count bytes to an output stream, starting from the given offset position  Can freeze for undefined time, until it sends all bytes to their destination  Flush()  Sends the internal buffers data to its destination (data storage, I/O device, etc.) Methods of System.IO.Stream Class (2) 19
  • 20.  Close()  Calls Flush()  Closes the connection to the device (mechanism)  Releases the used resources  Seek(offset, SeekOrigin)  Moves the position (if supported) with given offset towards the beginning, the end or the current position Methods of System.IO.Stream Class (3) 20
  • 22.  Inherits the Stream class and supports all its methods and properties  Supports reading, writing, positioning operations, etc.  The constructor contains parameters for:  File name  File open mode  File access mode  Concurrent users access mode The FileStream Class 22
  • 23.  FileMode – opening file mode  Open, Append, Create, CreateNew, OpenOrCreate, Truncate  FileAccess – operations mode for the file  Read, Write, ReadWrite  FileShare – access rules for other users while file is opened  None, Read, Write, ReadWrite The FileStream Class (2) 23 Optional parameters var fs = new FileStream(string fileName, FileMode, [FileAccess], [FileShare]);
  • 24. Writing Text to File – Example 24 string text = "Кирилица"; var fileStream = new FileStream("../../log.txt", FileMode.Create); try { byte[] bytes = Encoding.UTF8.GetBytes(text); fileStream.Write(bytes, 0, bytes.Length); } finally { fileStream.Close(); } try-finally guarantees the stream will always close Encoding.UTF8.GetBytes() returns the underlying bytes of the character
  • 25.  Slice the file sliceMe.txt in 4 equal parts  Name them  Part-1.txt  Part-2.txt  Part-3.txt  Part-4.txt Problem: Slice File 25
  • 26. Solution: Slice File 26 string destinationDirectory = ""; //Add saving path string sourceFile = ""; //Add file path int parts = 4; List<string> files = new List<string> { "Part-1.txt", "Part- 2.txt ", "Part-3.txt ", "Part-4.txt" }; using (var streamReadFile = new FileStream(sourceFile, FileMode.Open)){ long pieceSize = (long)Math.Ceiling((double)streamReadFile.Length / parts); for (int i = 0; i < parts; i++){ long currentPieceSize = 0; //Continue to next slide }}
  • 27. Solution: Slice File(2) 27 using (var streamCreateFile = new FileStream(files[i], FileMode.Create)){ byte[] buffer = new byte[4096]; while ((streamReadFile.Read(buffer, 0, buffer.Length)) == buffer.Length){ currentPieceSize += buffer.Length; streamCreateFile.Write(buffer, 0, buffer.Length); if (currentPieceSize >= pieceSize){break;} } }
  • 28. File Class in .NET .NET API for Easily Working with Files
  • 29.  File.ReadAllText()  string – reads a text file at once  File.ReadAllLines()  string[] – reads a text file's lines Reading Text Files 29 using System.IO; … string text = File.ReadAllText("file.txt"); using System.IO; … string[] lines = File.ReadAllLines("file.txt");
  • 30.  Writing a string to a text file:  Writing a sequence of strings to a text file, at separate lines:  Appending additional text to an existing file: Writing Text Files 30 string[] names = { "peter", "irina", "george", "maria" }; File.WriteAllLines("output.txt", names); File.WriteAllText("output.txt", "Files are fun :)"); File.AppendAllText("output.txt", "nMore textn");
  • 31. Directory Class in .NET .NET API for Working with Directories
  • 32.  Creating a directory (with all its subdirectories at the specified path), unless they already exists:  Deleting a directory (with its contents):  Moving a file or a directory to a new location: Basic Directory Operations 32 Directory.CreateDirectory("TestFolder"); Directory.Delete("TestFolder", true); Directory.Move("Test", "New Folder");
  • 33.  GetFiles() – returns the names of the files (including their paths) in the specified directory  GetDirectories() – returns the names of the subdirectories (including their paths) in the specified directory Listing Directory Contents 33 string[] filesInDir = Directory.GetFiles("TestFolder"); string[] subDirs = Directory.GetDirectories("TestFolder");
  • 34.  You are given a folder named TestFolder  Calculate the size of all files in the folder (without subfolders)  Print the result in a file "output.txt" in Megabytes Problem: Calculate Folder Size 34 output.txt 5.16173839569092
  • 35. Solution: Calculate Folder Size 35 string[] files = Directory.GetFiles("TestFolder"); double sum = 0; foreach (string file in files) { FileInfo fileInfo = new FileInfo(file); sum += fileInfo.Length; } sum = sum / 1024 / 1024; File.WriteAllText("оutput.txt", sum.ToString());
  • 37.  …  …  … Summary 37  Streams are ordered sequences of bytes  Serve as I/O mechanisms  Can be read or written to (or both)  Always close streams by using try-finally or using(…)  Use the File class to work with files  Use the Directory class to work with directories
  • 41.  Software University – High-Quality Education and Employment Opportunities  softuni.bg  Software University Foundation  http://softuni.foundation/  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg Trainings @ Software University (SoftUni)
  • 42.  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution-NonCom mercial-ShareAlike 4.0 International" license License 42

Notes de l'éditeur

  1. (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  2. Icons by Chanut is Industries / Pixel perfect at http://www.flaticon.com/
  3. (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  4. (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  5. (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  6. (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  7. (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  8. (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  9. (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  10. (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*