Files, Directories, Exceptions

Slides:



Advertisements
Similar presentations
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Advertisements

Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
Strings and Text Processing
Graphs and Graph Algorithms
Version Control Systems
Auto Mapping Objects SoftUni Team Database Applications
Static Members and Namespaces
Functional Programming
Databases basics Course Introduction SoftUni Team Databases basics
Abstract Classes, Abstract Methods, Override Methods
Sets, Hash table, Dictionaries
C# Basic Syntax, Visual Studio, Console Input / Output
Interface Segregation / Dependency Inversion
Data Structures Course Overview SoftUni Team Data Structures
C# Basic Syntax, Visual Studio, Console Input / Output
Introduction to MVC SoftUni Team Introduction to MVC
PHP MVC Frameworks Course Introduction SoftUni Team Technical Trainers
Reflection SoftUni Team Technical Trainers Java OOP Advanced
Linear Data Structures: Stacks and Queues
Introduction to Entity Framework
Classes, Properties, Constructors, Objects, Namespaces
Mocking tools for easier unit testing
Parsing JSON JSON.NET, LINQ-to-JSON
EF Code First (Advanced)
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
Using Streams, Files, Serialization
Processing Sequences of Elements
Multi-Dictionaries, Nested Dictionaries, Sets
Heaps and Priority Queues
Entity Framework: Code First
Parsing XML XDocument and LINQ
Repeating Code Multiple Times
Inheritance Class Hierarchies SoftUni Team Technical Trainers C# OOP
Basic Tree Data Structures
Databases advanced Course Introduction SoftUni Team Databases advanced
Arrays, Lists, Stacks, Queues
Balancing Binary Search Trees, Rotations
Debugging and Troubleshooting Code
Entity Framework: Relations
Fast String Manipulation
Array and List Algorithms
Functional Programming
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
Processing Variable-Length Sequences of Elements
Transactions in Entity Framework
Regular Expressions (RegEx)
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Numeral Types and Type Conversion
Databases Advanced Course Introduction SoftUni Team Databases Advanced
Combining Data Structures
Arrays and Multidimensional Arrays
Data Definition and Data Types
Multidimensional Arrays, Sets, Dictionaries
Extending functionality using Collections
Functional Programming
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Exporting and Importing Data
Iterators and Comparators
Reflection SoftUni Team Technical Trainers C# OOP Advanced
Spring Data Advanced Querying
Software Quality Assurance
Version Control Systems
Polymorphism, Interfaces, Abstract Classes
Text Processing and Regex API
/^Hel{2}o\s*World\n$/
File Types, Using Streams, Manipulating Files
Multidimensional Arrays
Presentation transcript:

Files, Directories, Exceptions Working with the File System and Handling Runtime Exceptions try-catch Files SoftUni Team Technical Trainers Software University http://softuni.bg

Table of Contents File Operations Directory Operations What are Exceptions? Handling Exceptions try-catch

sli.do #extended-softuni Questions? sli.do #extended-softuni

.NET API for Easily Working with Files File Class in .NET .NET API for Easily Working with Files

Reading Text Files File.ReadAllText()  string – reads a text file at once File.ReadAllLines()  string[] – reads a text file's lines using System.IO; … string text = File.ReadAllText("file.txt"); using System.IO; … string[] lines = File.ReadAllLines("file.txt");

Writing Text Files 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: File.WriteAllText("output.txt", "Files are fun :)"); string[] names = {"peter", "irina", "george", "maria"}; File.WriteAllLines("output.txt", names); File.AppendAllText("output.txt", "\nMore text\n");

Inspecting Files Use FileInfo to get information about a file: var info = new FileInfo("output.txt"); Console.WriteLine("File size: {0} bytes", info.Length); Console.WriteLine("Created at: {0}", info.CreationTime); Console.WriteLine("Path + name: {0}", info.FullName); Console.WriteLine("File extension: {0}", info.Extension);

Problem: Odd Lines Write a program to read a text file lines.txt and extract its odd lines (starting from 0) in a text file odd-lines.txt File.ReadAllLines(…) method opens a text file, reads all lines of the file, and then closes the file. This method attempts to automatically detect the encoding of a file based on the presence of byte order marks. Encoding formats UTF-8 and UTF-32 (both big-endian and little-endian) can be detected. reads all lines of the file, and then closes the file. of a file based on the presence of byte order marks. little-endian) can be detected.

Solution: Odd Lines A better solution: string[] lines = File.ReadAllLines("lines.txt"); File.Delete("odd-lines.txt"); for (int i = 1; i < lines.Length; i += 2) File.AppendAllText("odd-lines.txt", lines[i] + Environment.NewLine); A better solution: string[] lines = File.ReadAllLines("lines.txt"); var oddLines = lines.Where((line, index) => index % 2 == 1); File.WriteAllLines("odd-lines.txt", oddLines);

Problem: Insert Line Numbers Read a text file input.txt line by line Insert line numbers in front of each line (start by 1) Write the result in a text file output.txt first line second line third line fourth line fifth line 1. first line 2. second line 3. third line 4. fourth line 5. fifth line

Solution: Line Numbers string[] lines = File.ReadAllLines("input.txt"); var numberedLines = lines.Select( (line, index) => $"{index+1}. {line}"); File.WriteAllLines("output.txt", numberedLines);

Problem: Word Count Read a list of words from words.txt and find how many times each word occurs (as case-insensitive) in a text file text.txt Write the results in results.txt Sort the words by frequency in descending order -I was quick to judge him, but it wasn't his fault. -Is this some kind of joke?! Is it? -Quick, hide here…It is safer. text.txt is -> 3 quick -> 2 fault -> 1 results.txt quick is fault words.txt

Solution: Word Count string[] words = File.ReadAllText("words.txt").ToLower().Split(); string[] text = File.ReadAllText("input.txt").ToLower() .Split(new char[] {'\n','\r',' ', '.', ',', '!', '?', '-'}, StringSplitOptions.RemoveEmptyEntries); var wordCount = new Dictionary<string, int>(); foreach (string word in words) wordCount[word] = 0; foreach (string word in text) if (wordCount.ContainsKey(word)) wordCount[word]++; // Write the output (sorted) to a text file "results.txt"

.NET API for Working with Directories Directory Class in .NET .NET API for Working with Directories

Basic Directory Operations 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 directory to a new location: Directory.CreateDirectory("TestFolder"); Directory.Delete("TestFolder", true); Directory.Move("Test", "New Folder");

Listing Directory Contents GetFiles() – returns the names of files (including their paths) in the specified directory GetDirectories() – returns the names of subdirectories (including their paths) in the specified directory string[] filesInDir = Directory.GetFiles("TestFolder"); string[] subDirs = Directory.GetDirectories("TestFolder");

Problem: Calculate Folder Size 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 output.txt 5.16173839569092

Solution: Calculate Folder Size 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());

Signaling about and Handling Runtime Errors * Exceptions Signaling about and Handling Runtime Errors (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

* What are Exceptions? Exceptions are a powerful mechanism for centralized handling of errors and unusual events Raised at runtime, when a problem occurs Can be caught and handled (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

The System.Exception Class The System.Exception class is base for all exceptions in .NET Holds information about the problem Message – problem description (text) StackTrace –snapshot of the stack © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

* Handling Exceptions (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

The try-catch Statement * The try-catch Statement Catching exceptions: try { // Do some work that can cause an exception } catch // This block will execute if any type of exception occurs (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

The try-catch Statement (2) * The try-catch Statement (2) Catching a certain exception types only: try { // Do some work that can cause an exception } catch (FormatException formatException) // This block will execute only if format exception occurs (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

The try-finally Statement * The try-finally Statement Ensures execution of given block in all cases When exception is raised or not in the try block Used for execution of cleaning-up code, e.g. releasing resources try { // Do some work that can cause an exception } finally // This block will always execute (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

The try-catch-finally Statement * The try-catch-finally Statement try { // Do some work that can cause an exception } catch(FileNotFoundException fileNotFoundEx) // This block will be executed only if // "file not found" exception occurs finally // This block will always execute (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

Summary Use the File class to work with files Create / modify / read / write / delete files Use the Directory class to work with directories Create / delete directories / list files / folders Exceptions provide error handling mechanism Hold information about a runtime error Can be caught and handled try-catch

Files, Directories and Exceptions https://softuni.bg/courses/programming-fundamentals © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Trainings @ Software University Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University Foundation softuni.org Software University @ Facebook facebook.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.