SlideShare ist ein Scribd-Unternehmen logo
1 von 61
Downloaden Sie, um offline zu lesen
Tool Development
Chapter 03: File I/O
Nick PrĂźhs
Assignment Solution #2
DEMO
2 / 58
Objectives
• To learn how to approach common I/O tasks in
.NET
• To understand the best practices of file and stream
I/O in general
• To get an overview of the data display controls of
WPF
3 / 58
Streams
• Sequence of bytes read from or written to a backing
store (e.g. disk, memory)
• Provide three fundamental operations:
• Reading
• Writing
• Seeking
• Abstraction from the specific details of the operation
system and underlying devices
• FileStream
• NetworkStream
• MemoryStream
• CryptoStream
4 / 58
Files
• Ordered and names collection of bytes that have
persistent storage
• Disks contain directories, directories contain files
• Can be created, copied, deleted, moved, read from
and written to
5 / 58
File I/O in .NET
• System.IO namespace features classes for…
• Reading from files and streams
• Writing to files and streams
• Accessing file and directory information
• Readers and Writers wrap streams to handle
conversion of encoded characters to and from
bytes
• BinaryReader, BinaryWriter
• TextReader, TextWriter
6 / 58
FileInfo Class
• Provides typical operations such as copying,
moving, renaming, creating, opening, deleting, and
appending to files
• Can be faster for performing multiple operations on
the same file, because a security check will not
always be necessary
• Grants full read/write access to new files by default
7 / 58
Creating New Files
C#
8 / 58
// Collect information on the file to create.
FileInfo fileInfo = new FileInfo("newFile.txt");
// Create new file.
FileStream fileStream = fileInfo.Create();
// ...
// Close file stream and release all resources.
fileStream.Close();
Gotcha!
You should always release any files
after you’re finished!
The user will thank you for that.
9 / 58
File In Use
10 / 78
Writing Text To Files
C#
11 / 58
// Collect information on the file to create.
FileInfo fileInfo = new FileInfo("newFile.txt");
// Create new file.
FileStream fileStream = fileInfo.Create();
// Create new text writer.
TextWriter textWriter = new StreamWriter(fileStream);
// Write text.
textWriter.WriteLine("Hello World!");
// Close file stream and release all resources.
textWriter.Close();
Writing Encoded Text To Files
C#
12 / 58
// Collect information on the file to create.
FileInfo fileInfo = new FileInfo("newFile.txt");
// Create new file.
FileStream fileStream = fileInfo.Create();
// Create new text writer.
TextWriter textWriter = new StreamWriter(fileStream, Encoding.UTF8);
// Write text.
textWriter.WriteLine("Hello World!");
// Close file stream and release all resources.
textWriter.Close();
Reading Text From Files
C#
13 / 58
// Collect information on the file to read from.
FileInfo fileInfo = new FileInfo("newFile.txt");
// Open file for reading.
FileStream fileStream = fileInfo.OpenRead();
// Create new text reader.
TextReader textReader = new StreamReader(fileStream);
// Read text.
string s;
while ((s = textReader.ReadLine()) != null)
{
Console.WriteLine(s);
}
// Close file stream and release all resources.
textReader.Close();
Appending Text To Files
C#
14 / 58
// Collect information on the file to append text to.
FileInfo fileInfo = new FileInfo("newFile.txt");
// Open file for writing.
TextWriter textWriter = fileInfo.AppendText();
// Append text.
textWriter.WriteLine("new line");
// Close file stream and release all resources.
textWriter.Close();
Renaming and Moving Files
C#
15 / 58
// Collect information on the file to rename.
FileInfo fileInfo = new FileInfo("newFile.txt");
// Rename file.
fileInfo.MoveTo("movedFile.txt");
Deleting Files
C#
16 / 58
// Collect information on the file to delete.
FileInfo fileInfo = new FileInfo("newFile.txt");
// Delete file.
fileInfo.Delete();
Checking Whether Files Exist
C#
17 / 58
// Collect information on the file to delete.
FileInfo fileInfo = new FileInfo("newFile.txt");
// Check if file exists.
if (fileInfo.Exists)
{
// Delete file.
fileInfo.Delete();
}
Accessing File Info
C#
18 / 58
// Collect information on the file.
FileInfo fileInfo = new FileInfo("newFile.txt");
// Show information on console.
Console.WriteLine("File name: {0}", fileInfo.Name);
Console.WriteLine("File size (in bytes): {0}", fileInfo.Length);
Console.WriteLine("Read-only: {0}", fileInfo.IsReadOnly);
Console.WriteLine("Modified: {0}", fileInfo.LastWriteTime);
Accessing File Info
C#
19 / 58
// Collect information on the file.
FileInfo fileInfo = new FileInfo("newFile.txt");
// Show information on console.
Console.WriteLine("File name: {0}", fileInfo.Name);
Console.WriteLine("File size (in bytes): {0}", fileInfo.Length);
Console.WriteLine("Read-only: {0}", fileInfo.IsReadOnly);
Console.WriteLine("Modified: {0}", fileInfo.LastWriteTime);
Console Output
File name: newFile.txt
File size (in bytes): 10
Read-only: False
Modified: 11/3/2013 3:51:13 PM
Writing Binary Data To Files
C#
20 / 58
// Collect information on the file to create.
FileInfo fileInfo = new FileInfo("newFile.dat");
// Create new file.
FileStream fileStream = fileInfo.Create();
// Create new binary writer.
BinaryWriter binaryWriter = new BinaryWriter(fileStream);
// Write data.
binaryWriter.Write(23);
binaryWriter.Write(true);
binaryWriter.Write(0.4f);
// Close file stream and release all resources.
binaryWriter.Close();
Reading From Binary Files
C#
21 / 58
// Collect information on the file to read from.
FileInfo fileInfo = new FileInfo("newFile.dat");
// Open file for reading.
FileStream fileStream = fileInfo.OpenRead();
// Create new binary reader.
BinaryReader binaryReader = new BinaryReader(fileStream);
// Read data.
int i = binaryReader.ReadInt32();
bool b = binaryReader.ReadBoolean();
float f = binaryReader.ReadSingle();
// Close file stream and release all resources.
binaryReader.Close();
File Access Rights
• When opening a file, you have to request the
required access right from the underlying operating
system
• Read access
• Write access
• You can request either exclusive or non-exclusive
access rights, possibly preventing future access to
the file until you release it again
22 / 58
Exclusive Reading
C#
23 / 58
// Collect information on the file to read from.
FileInfo fileInfo = new FileInfo("newFile.txt");
// Open file for exclusive reading.
FileStream fileStream = fileInfo.OpenRead();
// Create new text reader.
TextReader textReader = new StreamReader(fileStream);
Exclusive Reading
C#
24 / 58
// Collect information on the file to read from.
FileInfo fileInfo = new FileInfo("newFile.txt");
// Open file for exclusive reading.
FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read);
// Create new text reader.
TextReader textReader = new StreamReader(fileStream);
Shared Reading
C#
25 / 58
// Collect information on the file to read from.
FileInfo fileInfo = new FileInfo("newFile.txt");
// Open file for shared reading.
FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
// Create new text reader.
TextReader textReader = new StreamReader(fileStream);
The interface IDisposable
• Primary use of this interface is to release unmanaged
resources
• Garbage collector automatically releases the memory
allocated to a managed object when that object is no longer
used
• However, it is not possible to predict when garbage collection
will occur.
• Furthermore, the garbage collector has no knowledge of
unmanaged resources such as window handles, or open files
and streams
• Use the Dispose method of this interface to explicitly
release unmanaged resources in conjunction with the
garbage collector.
26 / 78
The using Statement
• Provides a convenient syntax that ensures the
correct use of IDisposable objects
• As a rule, when you use an IDisposable object,
you should declare and instantiate it in a using
statement
• Calls the Dispose method on the object in the correct
way, and causes the object itself to go out of scope as
soon as Dispose is called
• Ensures that Dispose is called even if an exception
occurs while you are calling methods on the object
• Within the using block, the object is read-only and
cannot be modified or reassigned
27 / 78
Writing Text To Files
C#
28 / 58
// Collect information on the file to create.
FileInfo fileInfo = new FileInfo("newFile.txt");
// Create new file.
using (FileStream fileStream = fileInfo.Create())
{
// Create new text writer.
using (TextWriter textWriter = new StreamWriter(fileStream, Encoding.UTF8))
{
// Write text.
textWriter.WriteLine("Hello World!");
}
}
DirectoryInfo Class
• Same as FileInfo, just for directories
• Create method
• CreateSubdirectory method
• MoveTo method
• Delete method
• Exists property
• Parent property
29 / 58
Enumerating Directory Files
C#
30 / 58
// Collect information on the directory to enumerate all text files of.
DirectoryInfo directoryInfo = new DirectoryInfo(".");
// Enumerate all files in the directory.
IEnumerable<FileInfo> files = directoryInfo.EnumerateFiles("*.txt");
// Show file names on console.
foreach (FileInfo file in files)
{
Console.WriteLine(file.Name);
}
Enumerating Directory Files
C#
31 / 58
// Collect information on the directory to enumerate all text files of.
DirectoryInfo directoryInfo = new DirectoryInfo(".");
// Recursively enumerate all files in the directory.
IEnumerable<FileInfo> files = directoryInfo.EnumerateFiles("*.txt", SearchOption.AllDirectories);
// Show file names on console.
foreach (FileInfo file in files)
{
Console.WriteLine(file.FullName);
}
Compressing and
Extracting Directories
C#
32 / 58
// Compress directory to zip file.
ZipFile.CreateFromDirectory("content", "archive.zip");
// Extract directory from zip file.
ZipFile.ExtractToDirectory("archive.zip", "extracted");
Gotcha!
To use the ZipFile class, you must
reference the assembly
System.IO.Compression.FileSystem.
33 / 78
Compressing and
Extracting Single Files
C#
34 / 78
const string OutputDirectory = "extracted";
if (!Directory.Exists(OutputDirectory))
{
Directory.CreateDirectory(OutputDirectory);
}
// Open zip file for reading.
using (ZipArchive archive = ZipFile.OpenRead("archive.zip"))
{
// Iterate all archive files.
foreach (ZipArchiveEntry entry in archive.Entries)
{
// Extract file.
entry.ExtractToFile(Path.Combine(OutputDirectory, entry.FullName));
}
}
Compositing Streams
• The design of the System.IO classes provides
simplified stream composing
• Base streams can be attached to one or more pass-
through streams that provide the functionality you
want
• Reader or writer is attached to the end of the chain
35 / 58
Compositing Streams
C#
36 / 58
// Collect information on the file to create.
FileInfo fileInfo = new FileInfo("newFile.gz");
// Create new file.
using (FileStream fileStream = fileInfo.Create())
{
// Create compression stream.
using (GZipStream compressionStream = new GZipStream(fileStream, CompressionMode.Compress))
{
// Create new text writer.
using (TextWriter textWriter = new StreamWriter(compressionStream))
{
// Write text.
textWriter.WriteLine("Hello World!");
}
}
}
Common Exceptions
• UnauthorizedAccessException
• Example: Destination is read-only.
• ArgumentException
• Example: Destination path contains invalid characters.
• ArgumentNullException
• Example: Destination path is null.
• FileNotFoundException
• Example: File not found.
• IOException
• Example: Destination file already exists.
37 / 58
Hint
Check MSDN documentation for
thrown exceptions whenever you
work with System.IO classes.
38 / 78
Data Binding in WPF
• Allows users to view and edit data:
• Copies data from managed objects into controls, where
the data can be displayed and edited
• Ensures that changes made to data by using controls are
copied back to the managed objects
• Core unit of the data binding engine is the
Binding class
• Binds a control (the binding target) to a data object (the
binding source
39 / 58
Data Binding Example
XAML
40 / 58
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication1.MainWindow">
<!-- Bind the TextBox to the data source (TextBox.Text to Person.Name). -->
<TextBox Name="personNameTextBox" Text="{Binding Path=Name}" />
</Window>
Data Binding Example
C#
41 / 58
namespace WpfApplication1
{
public class Person
{
private string name = "No Name";
public string Name
{
get { return this.name; }
set { this.name = value; }
}
}
}
Data Binding Example
C#
42 / 58
namespace WpfApplication1
{
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
// Create Person data source.
Person person = new Person();
// Make data source available for binding.
this.DataContext = person;
}
}
}
DataGrid Control
Provides a flexible way to display a collection of data
in rows and columns.
Rendered View
43 / 58
DataGrid Control
Provides a flexible way to display a collection of data
in rows and columns.
Rendered View
44 / 58
DataGrid Control
XAML
45 / 58
<DataGrid x:Name="TileTypeGrid" ItemsSource="{Binding}“ />
C#
List<MapTileType> tileTypes = new List<MapTileType>
{
new MapTileType(3, "Desert"),
new MapTileType(5, "Water"),
new MapTileType(1, "Grass")
};
this.TileTypeGrid.DataContext = tileTypes;
Updating DataGrid Controls
• Updates automatically when items are added to or
removed from the source data, if bound to a
collection that implements the
INotifyCollectionChanged interface
• Example: ObservableCollection<T>
• Automatically reflects property changes, if the
objects in the collection implement the
INotifyPropertyChanged interface
46 / 58
DataGrid Control Content
• Generates columns automatically
• Type of column that is generated depends on the
type of data in the column
• String: Label
• Bool: CheckBox
• Enum: ComboBox
47 / 58
DataGrid Control Selection
• SelectionMode property specifies whether a user
can select cells, full rows, or both
• SelectionUnit property specifies whether multiple
rows/cells can be selected, or only single rows/cells
• SelectedCells property contains cells that are
currently selected
• SelectedCellsChanged event is raised for cells for
which selection has changed
48 / 58
DataGrid Control Editing
• IsReadOnly property disables editing
• CanUserAddRows and CanUserDeleteRows
properties specify whether a user can add or delete
rows
• Provides BeginEdit, CommitEdit, and CancelEdit
commands
49 / 58
TreeView Control
Displays hierarchical data in a tree structure that has
items that can expand and collapse.
Rendered View
50 / 58
TreeView Control
XAML
51 / 58
<TreeView>
<TreeViewItem Header="Abilities">
<TreeViewItem Header="Fireball"/>
<TreeViewItem Header="Frostbolt"/>
</TreeViewItem>
<TreeViewItem Header="Items">
<TreeViewItem Header="Ring of Dominace +3"/>
</TreeViewItem>
</TreeView>
TreeView Control
C#
52 / 58
TreeViewItem abilitiesRoot = new TreeViewItem { Header = "Abilities" };
abilitiesRoot.Items.Add(new TreeViewItem { Header = "Fireball" });
abilitiesRoot.Items.Add(new TreeViewItem { Header = "Frostbolt" });
TreeViewItem itemsRoot = new TreeViewItem { Header = "Items" };
itemsRoot.Items.Add(new TreeViewItem { Header = "Ring of Dominance +3" });
this.ObjectTree.Items.Add(abilitiesRoot);
this.ObjectTree.Items.Add(itemsRoot);
TabControl
Contains multiple items that share the same space
on the screen.
Rendered View
53 / 58
TabControl
XAML
54 / 58
<TabControl>
<TabItem Header="Tab 1">
<TextBlock>Content of Tab 1</TextBlock>
</TabItem>
<TabItem Header="Tab 2">
<TextBlock>Content of Tab 2</TextBlock>
</TabItem>
</TabControl>
Assignment #3
1. Map Sprites
1. Create a sprite (.png file) for each of your terrain types
and add it to the project.
2. Load all sprites on startup of your application by
creating and storing BitmapImage objects. You can
access project resources in image URIs as follows:
image.UriSource = new
Uri("pack://application:,,,/Desert.png");
55 / 58
Assignment #3
2. Map Canvas
1. Add a canvas to your main window.
2. Reset the map canvas whenever a new map is
created:
1. Remove all children.
2. Add Image children to the canvas.
3. Set the position of these children using Canvas.SetLeft and
Canvas.SetTop.
56 / 58
Assignment #3
3. Scrolling
Parent the map canvas to a ScrollViewer to enable
scrolling across the map.
57 / 58
Assignment #3
4. Brush
1. Add a brush selection to your main window.
2. Enable drawing on the map canvas.
1. Modify the map model whenever the user clicks on a map
canvas image. You can use the Tag property of an image to
store its position, and the MouseLeftButtonDown,
MouseLeftButtonUp and MouseMove events for handling user
input.
2. Update the map canvas with the new tile at the clicked
position.
58 / 58
References
• MSDN. WPF Controls by Category.
https://msdn.microsoft.com/en-
us/library/ms754204%28v=vs.100%29.aspx, May 2016.
• MSDN. File and Stream I/O.
http://msdn.microsoft.com/en-
us/library/k3352a4t%28v=vs.110%29.aspx, May 2016.
• MSDN. Common I/O Tasks.
http://msdn.microsoft.com/en-
us/library/ms404278%28v=vs.110%29.aspx, May 2016.
• MSDN. using Statement (C# Reference).
http://msdn.microsoft.com/en-
us/library/yh598w02(v=vs.120).aspx, May 2016.
59 / 58
Thank you!
http://www.npruehs.de
https://github.com/npruehs
@npruehs
dev@npruehs.de
5 Minute Review Session
• Which different WPF data controls do you know?
• What are the three fundamental operations provided by
streams?
• Point out the difference between streams and files!
• Which namespaces and classes does .NET provide for
stream and file handling?
• What’s the point of closing a stream, and how do you do
that?
• Which types of file access rights do you know?
• Why and how are streams composited in .NET?
• What are the most common I/O exceptions in .NET?
• How do you bind data to a WPF control?
61 / 58

Weitere ähnliche Inhalte

Was ist angesagt?

Windows Registry Analysis
Windows Registry AnalysisWindows Registry Analysis
Windows Registry AnalysisHimanshu0734
 
Leveraging NTFS Timeline Forensics during the Analysis of Malware
Leveraging NTFS Timeline Forensics during the Analysis of MalwareLeveraging NTFS Timeline Forensics during the Analysis of Malware
Leveraging NTFS Timeline Forensics during the Analysis of Malwaretmugherini
 
Modern Kernel Pool Exploitation: Attacks and Techniques
Modern Kernel Pool Exploitation: Attacks and TechniquesModern Kernel Pool Exploitation: Attacks and Techniques
Modern Kernel Pool Exploitation: Attacks and TechniquesMichael Scovetta
 
Chapter 4 1
Chapter 4 1Chapter 4 1
Chapter 4 1lopjuan
 
NTFS and Inode
NTFS and InodeNTFS and Inode
NTFS and InodeAmit Seal Ami
 
Ntfs and computer forensics
Ntfs and computer forensicsNtfs and computer forensics
Ntfs and computer forensicsGaurav Ragtah
 
Registry Forensics
Registry ForensicsRegistry Forensics
Registry ForensicsSomesh Sawhney
 
File Handling
File HandlingFile Handling
File HandlingWaqar Ali
 
Windows forensic
Windows forensicWindows forensic
Windows forensicMD SAQUIB KHAN
 
Windows Forensics
Windows ForensicsWindows Forensics
Windows ForensicsPrince Boonlia
 
Windows Registry Forensics - Artifacts
Windows Registry Forensics - Artifacts Windows Registry Forensics - Artifacts
Windows Registry Forensics - Artifacts MD SAQUIB KHAN
 
03 Intro Firecat LAN
03 Intro Firecat LAN03 Intro Firecat LAN
03 Intro Firecat LANEvan Merrill
 
Free Space Management, Efficiency & Performance, Recovery and NFS
Free Space Management, Efficiency & Performance, Recovery and NFSFree Space Management, Efficiency & Performance, Recovery and NFS
Free Space Management, Efficiency & Performance, Recovery and NFSUnited International University
 

Was ist angesagt? (19)

File handling
File handlingFile handling
File handling
 
Windows registry forensics
Windows registry forensicsWindows registry forensics
Windows registry forensics
 
Windows Registry Analysis
Windows Registry AnalysisWindows Registry Analysis
Windows Registry Analysis
 
Leveraging NTFS Timeline Forensics during the Analysis of Malware
Leveraging NTFS Timeline Forensics during the Analysis of MalwareLeveraging NTFS Timeline Forensics during the Analysis of Malware
Leveraging NTFS Timeline Forensics during the Analysis of Malware
 
Modern Kernel Pool Exploitation: Attacks and Techniques
Modern Kernel Pool Exploitation: Attacks and TechniquesModern Kernel Pool Exploitation: Attacks and Techniques
Modern Kernel Pool Exploitation: Attacks and Techniques
 
Ntfs forensics
Ntfs forensicsNtfs forensics
Ntfs forensics
 
Chapter 4 1
Chapter 4 1Chapter 4 1
Chapter 4 1
 
NTFS and Inode
NTFS and InodeNTFS and Inode
NTFS and Inode
 
Ntfs and computer forensics
Ntfs and computer forensicsNtfs and computer forensics
Ntfs and computer forensics
 
Registry Forensics
Registry ForensicsRegistry Forensics
Registry Forensics
 
File Handling
File HandlingFile Handling
File Handling
 
Contigious
ContigiousContigious
Contigious
 
Systems Programming - File IO
Systems Programming - File IOSystems Programming - File IO
Systems Programming - File IO
 
Windows forensic
Windows forensicWindows forensic
Windows forensic
 
Windows Forensics
Windows ForensicsWindows Forensics
Windows Forensics
 
Windows Registry Forensics - Artifacts
Windows Registry Forensics - Artifacts Windows Registry Forensics - Artifacts
Windows Registry Forensics - Artifacts
 
03 Intro Firecat LAN
03 Intro Firecat LAN03 Intro Firecat LAN
03 Intro Firecat LAN
 
Windows forensic artifacts
Windows forensic artifactsWindows forensic artifacts
Windows forensic artifacts
 
Free Space Management, Efficiency & Performance, Recovery and NFS
Free Space Management, Efficiency & Performance, Recovery and NFSFree Space Management, Efficiency & Performance, Recovery and NFS
Free Space Management, Efficiency & Performance, Recovery and NFS
 

Ähnlich wie Tool Development 03 - File I/O

Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Switching & Multiplexing
Switching & MultiplexingSwitching & Multiplexing
Switching & MultiplexingMelkamuEndale1
 
File Input & Output
File Input & OutputFile Input & Output
File Input & OutputPRN USM
 
basics of file handling
basics of file handlingbasics of file handling
basics of file handlingpinkpreet_kaur
 
Basics of file handling
Basics of file handlingBasics of file handling
Basics of file handlingpinkpreet_kaur
 
Tool Development 06 - Binary Serialization, Worker Threads
Tool Development 06 - Binary Serialization, Worker ThreadsTool Development 06 - Binary Serialization, Worker Threads
Tool Development 06 - Binary Serialization, Worker ThreadsNick Pruehs
 
Chapter10
Chapter10Chapter10
Chapter10vishalw24
 
Create a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdfCreate a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdfshahidqamar17
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingChereLemma2
 
LinuxÂŽ Directory LogPOS420 Version 111University of Pho.docx
LinuxÂŽ Directory LogPOS420 Version 111University of Pho.docxLinuxÂŽ Directory LogPOS420 Version 111University of Pho.docx
LinuxÂŽ Directory LogPOS420 Version 111University of Pho.docxSHIVA101531
 
Log into your netlab workstation then ssh to server.cnt1015.local wi.docx
Log into your netlab workstation then ssh to server.cnt1015.local wi.docxLog into your netlab workstation then ssh to server.cnt1015.local wi.docx
Log into your netlab workstation then ssh to server.cnt1015.local wi.docxdesteinbrook
 
Input output files in java
Input output files in javaInput output files in java
Input output files in javaKavitha713564
 

Ähnlich wie Tool Development 03 - File I/O (20)

Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Switching & Multiplexing
Switching & MultiplexingSwitching & Multiplexing
Switching & Multiplexing
 
File Input & Output
File Input & OutputFile Input & Output
File Input & Output
 
File operations
File operationsFile operations
File operations
 
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
 
File Handling
File HandlingFile Handling
File Handling
 
File Handling
File HandlingFile Handling
File Handling
 
Tool Development 06 - Binary Serialization, Worker Threads
Tool Development 06 - Binary Serialization, Worker ThreadsTool Development 06 - Binary Serialization, Worker Threads
Tool Development 06 - Binary Serialization, Worker Threads
 
Pos 433 pos433
Pos 433 pos433Pos 433 pos433
Pos 433 pos433
 
Chapter10
Chapter10Chapter10
Chapter10
 
Create a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdfCreate a text file named lnfo.txt. Enter the following informatio.pdf
Create a text file named lnfo.txt. Enter the following informatio.pdf
 
using System.docx
using System.docxusing System.docx
using System.docx
 
File Management and manipulation in C++ Programming
File Management and manipulation in C++ ProgrammingFile Management and manipulation in C++ Programming
File Management and manipulation in C++ Programming
 
LinuxÂŽ Directory LogPOS420 Version 111University of Pho.docx
LinuxÂŽ Directory LogPOS420 Version 111University of Pho.docxLinuxÂŽ Directory LogPOS420 Version 111University of Pho.docx
LinuxÂŽ Directory LogPOS420 Version 111University of Pho.docx
 
data file handling
data file handlingdata file handling
data file handling
 
File Organization
File OrganizationFile Organization
File Organization
 
Log into your netlab workstation then ssh to server.cnt1015.local wi.docx
Log into your netlab workstation then ssh to server.cnt1015.local wi.docxLog into your netlab workstation then ssh to server.cnt1015.local wi.docx
Log into your netlab workstation then ssh to server.cnt1015.local wi.docx
 
Input output files in java
Input output files in javaInput output files in java
Input output files in java
 
Lab 1 Essay
Lab 1 EssayLab 1 Essay
Lab 1 Essay
 

Mehr von Nick Pruehs

Unreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual EffectsUnreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual EffectsNick Pruehs
 
Unreal Engine Basics 05 - User Interface
Unreal Engine Basics 05 - User InterfaceUnreal Engine Basics 05 - User Interface
Unreal Engine Basics 05 - User InterfaceNick Pruehs
 
Unreal Engine Basics 04 - Behavior Trees
Unreal Engine Basics 04 - Behavior TreesUnreal Engine Basics 04 - Behavior Trees
Unreal Engine Basics 04 - Behavior TreesNick Pruehs
 
Unreal Engine Basics 03 - Gameplay
Unreal Engine Basics 03 - GameplayUnreal Engine Basics 03 - Gameplay
Unreal Engine Basics 03 - GameplayNick Pruehs
 
Unreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorUnreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorNick Pruehs
 
Unreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkUnreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkNick Pruehs
 
Game Programming - Cloud Development
Game Programming - Cloud DevelopmentGame Programming - Cloud Development
Game Programming - Cloud DevelopmentNick Pruehs
 
Game Programming - Git
Game Programming - GitGame Programming - Git
Game Programming - GitNick Pruehs
 
Eight Rules for Making Your First Great Game
Eight Rules for Making Your First Great GameEight Rules for Making Your First Great Game
Eight Rules for Making Your First Great GameNick Pruehs
 
Designing an actor model game architecture with Pony
Designing an actor model game architecture with PonyDesigning an actor model game architecture with Pony
Designing an actor model game architecture with PonyNick Pruehs
 
Game Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance OptimizationGame Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance OptimizationNick Pruehs
 
Scrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small TeamsScrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small TeamsNick Pruehs
 
Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)Nick Pruehs
 
What Would Blizzard Do
What Would Blizzard DoWhat Would Blizzard Do
What Would Blizzard DoNick Pruehs
 
School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsNick Pruehs
 
Tool Development A - Git
Tool Development A - GitTool Development A - Git
Tool Development A - GitNick Pruehs
 
Game Programming 12 - Shaders
Game Programming 12 - ShadersGame Programming 12 - Shaders
Game Programming 12 - ShadersNick Pruehs
 
Game Programming 11 - Game Physics
Game Programming 11 - Game PhysicsGame Programming 11 - Game Physics
Game Programming 11 - Game PhysicsNick Pruehs
 
Game Programming 10 - Localization
Game Programming 10 - LocalizationGame Programming 10 - Localization
Game Programming 10 - LocalizationNick Pruehs
 
Game Programming 09 - AI
Game Programming 09 - AIGame Programming 09 - AI
Game Programming 09 - AINick Pruehs
 

Mehr von Nick Pruehs (20)

Unreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual EffectsUnreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual Effects
 
Unreal Engine Basics 05 - User Interface
Unreal Engine Basics 05 - User InterfaceUnreal Engine Basics 05 - User Interface
Unreal Engine Basics 05 - User Interface
 
Unreal Engine Basics 04 - Behavior Trees
Unreal Engine Basics 04 - Behavior TreesUnreal Engine Basics 04 - Behavior Trees
Unreal Engine Basics 04 - Behavior Trees
 
Unreal Engine Basics 03 - Gameplay
Unreal Engine Basics 03 - GameplayUnreal Engine Basics 03 - Gameplay
Unreal Engine Basics 03 - Gameplay
 
Unreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorUnreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal Editor
 
Unreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkUnreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game Framework
 
Game Programming - Cloud Development
Game Programming - Cloud DevelopmentGame Programming - Cloud Development
Game Programming - Cloud Development
 
Game Programming - Git
Game Programming - GitGame Programming - Git
Game Programming - Git
 
Eight Rules for Making Your First Great Game
Eight Rules for Making Your First Great GameEight Rules for Making Your First Great Game
Eight Rules for Making Your First Great Game
 
Designing an actor model game architecture with Pony
Designing an actor model game architecture with PonyDesigning an actor model game architecture with Pony
Designing an actor model game architecture with Pony
 
Game Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance OptimizationGame Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance Optimization
 
Scrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small TeamsScrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small Teams
 
Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)
 
What Would Blizzard Do
What Would Blizzard DoWhat Would Blizzard Do
What Would Blizzard Do
 
School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine Basics
 
Tool Development A - Git
Tool Development A - GitTool Development A - Git
Tool Development A - Git
 
Game Programming 12 - Shaders
Game Programming 12 - ShadersGame Programming 12 - Shaders
Game Programming 12 - Shaders
 
Game Programming 11 - Game Physics
Game Programming 11 - Game PhysicsGame Programming 11 - Game Physics
Game Programming 11 - Game Physics
 
Game Programming 10 - Localization
Game Programming 10 - LocalizationGame Programming 10 - Localization
Game Programming 10 - Localization
 
Game Programming 09 - AI
Game Programming 09 - AIGame Programming 09 - AI
Game Programming 09 - AI
 

KĂźrzlich hochgeladen

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel AraĂşjo
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

KĂźrzlich hochgeladen (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Tool Development 03 - File I/O

  • 1. Tool Development Chapter 03: File I/O Nick PrĂźhs
  • 3. Objectives • To learn how to approach common I/O tasks in .NET • To understand the best practices of file and stream I/O in general • To get an overview of the data display controls of WPF 3 / 58
  • 4. Streams • Sequence of bytes read from or written to a backing store (e.g. disk, memory) • Provide three fundamental operations: • Reading • Writing • Seeking • Abstraction from the specific details of the operation system and underlying devices • FileStream • NetworkStream • MemoryStream • CryptoStream 4 / 58
  • 5. Files • Ordered and names collection of bytes that have persistent storage • Disks contain directories, directories contain files • Can be created, copied, deleted, moved, read from and written to 5 / 58
  • 6. File I/O in .NET • System.IO namespace features classes for… • Reading from files and streams • Writing to files and streams • Accessing file and directory information • Readers and Writers wrap streams to handle conversion of encoded characters to and from bytes • BinaryReader, BinaryWriter • TextReader, TextWriter 6 / 58
  • 7. FileInfo Class • Provides typical operations such as copying, moving, renaming, creating, opening, deleting, and appending to files • Can be faster for performing multiple operations on the same file, because a security check will not always be necessary • Grants full read/write access to new files by default 7 / 58
  • 8. Creating New Files C# 8 / 58 // Collect information on the file to create. FileInfo fileInfo = new FileInfo("newFile.txt"); // Create new file. FileStream fileStream = fileInfo.Create(); // ... // Close file stream and release all resources. fileStream.Close();
  • 9. Gotcha! You should always release any files after you’re finished! The user will thank you for that. 9 / 58
  • 11. Writing Text To Files C# 11 / 58 // Collect information on the file to create. FileInfo fileInfo = new FileInfo("newFile.txt"); // Create new file. FileStream fileStream = fileInfo.Create(); // Create new text writer. TextWriter textWriter = new StreamWriter(fileStream); // Write text. textWriter.WriteLine("Hello World!"); // Close file stream and release all resources. textWriter.Close();
  • 12. Writing Encoded Text To Files C# 12 / 58 // Collect information on the file to create. FileInfo fileInfo = new FileInfo("newFile.txt"); // Create new file. FileStream fileStream = fileInfo.Create(); // Create new text writer. TextWriter textWriter = new StreamWriter(fileStream, Encoding.UTF8); // Write text. textWriter.WriteLine("Hello World!"); // Close file stream and release all resources. textWriter.Close();
  • 13. Reading Text From Files C# 13 / 58 // Collect information on the file to read from. FileInfo fileInfo = new FileInfo("newFile.txt"); // Open file for reading. FileStream fileStream = fileInfo.OpenRead(); // Create new text reader. TextReader textReader = new StreamReader(fileStream); // Read text. string s; while ((s = textReader.ReadLine()) != null) { Console.WriteLine(s); } // Close file stream and release all resources. textReader.Close();
  • 14. Appending Text To Files C# 14 / 58 // Collect information on the file to append text to. FileInfo fileInfo = new FileInfo("newFile.txt"); // Open file for writing. TextWriter textWriter = fileInfo.AppendText(); // Append text. textWriter.WriteLine("new line"); // Close file stream and release all resources. textWriter.Close();
  • 15. Renaming and Moving Files C# 15 / 58 // Collect information on the file to rename. FileInfo fileInfo = new FileInfo("newFile.txt"); // Rename file. fileInfo.MoveTo("movedFile.txt");
  • 16. Deleting Files C# 16 / 58 // Collect information on the file to delete. FileInfo fileInfo = new FileInfo("newFile.txt"); // Delete file. fileInfo.Delete();
  • 17. Checking Whether Files Exist C# 17 / 58 // Collect information on the file to delete. FileInfo fileInfo = new FileInfo("newFile.txt"); // Check if file exists. if (fileInfo.Exists) { // Delete file. fileInfo.Delete(); }
  • 18. Accessing File Info C# 18 / 58 // Collect information on the file. FileInfo fileInfo = new FileInfo("newFile.txt"); // Show information on console. Console.WriteLine("File name: {0}", fileInfo.Name); Console.WriteLine("File size (in bytes): {0}", fileInfo.Length); Console.WriteLine("Read-only: {0}", fileInfo.IsReadOnly); Console.WriteLine("Modified: {0}", fileInfo.LastWriteTime);
  • 19. Accessing File Info C# 19 / 58 // Collect information on the file. FileInfo fileInfo = new FileInfo("newFile.txt"); // Show information on console. Console.WriteLine("File name: {0}", fileInfo.Name); Console.WriteLine("File size (in bytes): {0}", fileInfo.Length); Console.WriteLine("Read-only: {0}", fileInfo.IsReadOnly); Console.WriteLine("Modified: {0}", fileInfo.LastWriteTime); Console Output File name: newFile.txt File size (in bytes): 10 Read-only: False Modified: 11/3/2013 3:51:13 PM
  • 20. Writing Binary Data To Files C# 20 / 58 // Collect information on the file to create. FileInfo fileInfo = new FileInfo("newFile.dat"); // Create new file. FileStream fileStream = fileInfo.Create(); // Create new binary writer. BinaryWriter binaryWriter = new BinaryWriter(fileStream); // Write data. binaryWriter.Write(23); binaryWriter.Write(true); binaryWriter.Write(0.4f); // Close file stream and release all resources. binaryWriter.Close();
  • 21. Reading From Binary Files C# 21 / 58 // Collect information on the file to read from. FileInfo fileInfo = new FileInfo("newFile.dat"); // Open file for reading. FileStream fileStream = fileInfo.OpenRead(); // Create new binary reader. BinaryReader binaryReader = new BinaryReader(fileStream); // Read data. int i = binaryReader.ReadInt32(); bool b = binaryReader.ReadBoolean(); float f = binaryReader.ReadSingle(); // Close file stream and release all resources. binaryReader.Close();
  • 22. File Access Rights • When opening a file, you have to request the required access right from the underlying operating system • Read access • Write access • You can request either exclusive or non-exclusive access rights, possibly preventing future access to the file until you release it again 22 / 58
  • 23. Exclusive Reading C# 23 / 58 // Collect information on the file to read from. FileInfo fileInfo = new FileInfo("newFile.txt"); // Open file for exclusive reading. FileStream fileStream = fileInfo.OpenRead(); // Create new text reader. TextReader textReader = new StreamReader(fileStream);
  • 24. Exclusive Reading C# 24 / 58 // Collect information on the file to read from. FileInfo fileInfo = new FileInfo("newFile.txt"); // Open file for exclusive reading. FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read); // Create new text reader. TextReader textReader = new StreamReader(fileStream);
  • 25. Shared Reading C# 25 / 58 // Collect information on the file to read from. FileInfo fileInfo = new FileInfo("newFile.txt"); // Open file for shared reading. FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.Read); // Create new text reader. TextReader textReader = new StreamReader(fileStream);
  • 26. The interface IDisposable • Primary use of this interface is to release unmanaged resources • Garbage collector automatically releases the memory allocated to a managed object when that object is no longer used • However, it is not possible to predict when garbage collection will occur. • Furthermore, the garbage collector has no knowledge of unmanaged resources such as window handles, or open files and streams • Use the Dispose method of this interface to explicitly release unmanaged resources in conjunction with the garbage collector. 26 / 78
  • 27. The using Statement • Provides a convenient syntax that ensures the correct use of IDisposable objects • As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement • Calls the Dispose method on the object in the correct way, and causes the object itself to go out of scope as soon as Dispose is called • Ensures that Dispose is called even if an exception occurs while you are calling methods on the object • Within the using block, the object is read-only and cannot be modified or reassigned 27 / 78
  • 28. Writing Text To Files C# 28 / 58 // Collect information on the file to create. FileInfo fileInfo = new FileInfo("newFile.txt"); // Create new file. using (FileStream fileStream = fileInfo.Create()) { // Create new text writer. using (TextWriter textWriter = new StreamWriter(fileStream, Encoding.UTF8)) { // Write text. textWriter.WriteLine("Hello World!"); } }
  • 29. DirectoryInfo Class • Same as FileInfo, just for directories • Create method • CreateSubdirectory method • MoveTo method • Delete method • Exists property • Parent property 29 / 58
  • 30. Enumerating Directory Files C# 30 / 58 // Collect information on the directory to enumerate all text files of. DirectoryInfo directoryInfo = new DirectoryInfo("."); // Enumerate all files in the directory. IEnumerable<FileInfo> files = directoryInfo.EnumerateFiles("*.txt"); // Show file names on console. foreach (FileInfo file in files) { Console.WriteLine(file.Name); }
  • 31. Enumerating Directory Files C# 31 / 58 // Collect information on the directory to enumerate all text files of. DirectoryInfo directoryInfo = new DirectoryInfo("."); // Recursively enumerate all files in the directory. IEnumerable<FileInfo> files = directoryInfo.EnumerateFiles("*.txt", SearchOption.AllDirectories); // Show file names on console. foreach (FileInfo file in files) { Console.WriteLine(file.FullName); }
  • 32. Compressing and Extracting Directories C# 32 / 58 // Compress directory to zip file. ZipFile.CreateFromDirectory("content", "archive.zip"); // Extract directory from zip file. ZipFile.ExtractToDirectory("archive.zip", "extracted");
  • 33. Gotcha! To use the ZipFile class, you must reference the assembly System.IO.Compression.FileSystem. 33 / 78
  • 34. Compressing and Extracting Single Files C# 34 / 78 const string OutputDirectory = "extracted"; if (!Directory.Exists(OutputDirectory)) { Directory.CreateDirectory(OutputDirectory); } // Open zip file for reading. using (ZipArchive archive = ZipFile.OpenRead("archive.zip")) { // Iterate all archive files. foreach (ZipArchiveEntry entry in archive.Entries) { // Extract file. entry.ExtractToFile(Path.Combine(OutputDirectory, entry.FullName)); } }
  • 35. Compositing Streams • The design of the System.IO classes provides simplified stream composing • Base streams can be attached to one or more pass- through streams that provide the functionality you want • Reader or writer is attached to the end of the chain 35 / 58
  • 36. Compositing Streams C# 36 / 58 // Collect information on the file to create. FileInfo fileInfo = new FileInfo("newFile.gz"); // Create new file. using (FileStream fileStream = fileInfo.Create()) { // Create compression stream. using (GZipStream compressionStream = new GZipStream(fileStream, CompressionMode.Compress)) { // Create new text writer. using (TextWriter textWriter = new StreamWriter(compressionStream)) { // Write text. textWriter.WriteLine("Hello World!"); } } }
  • 37. Common Exceptions • UnauthorizedAccessException • Example: Destination is read-only. • ArgumentException • Example: Destination path contains invalid characters. • ArgumentNullException • Example: Destination path is null. • FileNotFoundException • Example: File not found. • IOException • Example: Destination file already exists. 37 / 58
  • 38. Hint Check MSDN documentation for thrown exceptions whenever you work with System.IO classes. 38 / 78
  • 39. Data Binding in WPF • Allows users to view and edit data: • Copies data from managed objects into controls, where the data can be displayed and edited • Ensures that changes made to data by using controls are copied back to the managed objects • Core unit of the data binding engine is the Binding class • Binds a control (the binding target) to a data object (the binding source 39 / 58
  • 40. Data Binding Example XAML 40 / 58 <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="WpfApplication1.MainWindow"> <!-- Bind the TextBox to the data source (TextBox.Text to Person.Name). --> <TextBox Name="personNameTextBox" Text="{Binding Path=Name}" /> </Window>
  • 41. Data Binding Example C# 41 / 58 namespace WpfApplication1 { public class Person { private string name = "No Name"; public string Name { get { return this.name; } set { this.name = value; } } } }
  • 42. Data Binding Example C# 42 / 58 namespace WpfApplication1 { public partial class MainWindow { public MainWindow() { InitializeComponent(); // Create Person data source. Person person = new Person(); // Make data source available for binding. this.DataContext = person; } } }
  • 43. DataGrid Control Provides a flexible way to display a collection of data in rows and columns. Rendered View 43 / 58
  • 44. DataGrid Control Provides a flexible way to display a collection of data in rows and columns. Rendered View 44 / 58
  • 45. DataGrid Control XAML 45 / 58 <DataGrid x:Name="TileTypeGrid" ItemsSource="{Binding}“ /> C# List<MapTileType> tileTypes = new List<MapTileType> { new MapTileType(3, "Desert"), new MapTileType(5, "Water"), new MapTileType(1, "Grass") }; this.TileTypeGrid.DataContext = tileTypes;
  • 46. Updating DataGrid Controls • Updates automatically when items are added to or removed from the source data, if bound to a collection that implements the INotifyCollectionChanged interface • Example: ObservableCollection<T> • Automatically reflects property changes, if the objects in the collection implement the INotifyPropertyChanged interface 46 / 58
  • 47. DataGrid Control Content • Generates columns automatically • Type of column that is generated depends on the type of data in the column • String: Label • Bool: CheckBox • Enum: ComboBox 47 / 58
  • 48. DataGrid Control Selection • SelectionMode property specifies whether a user can select cells, full rows, or both • SelectionUnit property specifies whether multiple rows/cells can be selected, or only single rows/cells • SelectedCells property contains cells that are currently selected • SelectedCellsChanged event is raised for cells for which selection has changed 48 / 58
  • 49. DataGrid Control Editing • IsReadOnly property disables editing • CanUserAddRows and CanUserDeleteRows properties specify whether a user can add or delete rows • Provides BeginEdit, CommitEdit, and CancelEdit commands 49 / 58
  • 50. TreeView Control Displays hierarchical data in a tree structure that has items that can expand and collapse. Rendered View 50 / 58
  • 51. TreeView Control XAML 51 / 58 <TreeView> <TreeViewItem Header="Abilities"> <TreeViewItem Header="Fireball"/> <TreeViewItem Header="Frostbolt"/> </TreeViewItem> <TreeViewItem Header="Items"> <TreeViewItem Header="Ring of Dominace +3"/> </TreeViewItem> </TreeView>
  • 52. TreeView Control C# 52 / 58 TreeViewItem abilitiesRoot = new TreeViewItem { Header = "Abilities" }; abilitiesRoot.Items.Add(new TreeViewItem { Header = "Fireball" }); abilitiesRoot.Items.Add(new TreeViewItem { Header = "Frostbolt" }); TreeViewItem itemsRoot = new TreeViewItem { Header = "Items" }; itemsRoot.Items.Add(new TreeViewItem { Header = "Ring of Dominance +3" }); this.ObjectTree.Items.Add(abilitiesRoot); this.ObjectTree.Items.Add(itemsRoot);
  • 53. TabControl Contains multiple items that share the same space on the screen. Rendered View 53 / 58
  • 54. TabControl XAML 54 / 58 <TabControl> <TabItem Header="Tab 1"> <TextBlock>Content of Tab 1</TextBlock> </TabItem> <TabItem Header="Tab 2"> <TextBlock>Content of Tab 2</TextBlock> </TabItem> </TabControl>
  • 55. Assignment #3 1. Map Sprites 1. Create a sprite (.png file) for each of your terrain types and add it to the project. 2. Load all sprites on startup of your application by creating and storing BitmapImage objects. You can access project resources in image URIs as follows: image.UriSource = new Uri("pack://application:,,,/Desert.png"); 55 / 58
  • 56. Assignment #3 2. Map Canvas 1. Add a canvas to your main window. 2. Reset the map canvas whenever a new map is created: 1. Remove all children. 2. Add Image children to the canvas. 3. Set the position of these children using Canvas.SetLeft and Canvas.SetTop. 56 / 58
  • 57. Assignment #3 3. Scrolling Parent the map canvas to a ScrollViewer to enable scrolling across the map. 57 / 58
  • 58. Assignment #3 4. Brush 1. Add a brush selection to your main window. 2. Enable drawing on the map canvas. 1. Modify the map model whenever the user clicks on a map canvas image. You can use the Tag property of an image to store its position, and the MouseLeftButtonDown, MouseLeftButtonUp and MouseMove events for handling user input. 2. Update the map canvas with the new tile at the clicked position. 58 / 58
  • 59. References • MSDN. WPF Controls by Category. https://msdn.microsoft.com/en- us/library/ms754204%28v=vs.100%29.aspx, May 2016. • MSDN. File and Stream I/O. http://msdn.microsoft.com/en- us/library/k3352a4t%28v=vs.110%29.aspx, May 2016. • MSDN. Common I/O Tasks. http://msdn.microsoft.com/en- us/library/ms404278%28v=vs.110%29.aspx, May 2016. • MSDN. using Statement (C# Reference). http://msdn.microsoft.com/en- us/library/yh598w02(v=vs.120).aspx, May 2016. 59 / 58
  • 61. 5 Minute Review Session • Which different WPF data controls do you know? • What are the three fundamental operations provided by streams? • Point out the difference between streams and files! • Which namespaces and classes does .NET provide for stream and file handling? • What’s the point of closing a stream, and how do you do that? • Which types of file access rights do you know? • Why and how are streams composited in .NET? • What are the most common I/O exceptions in .NET? • How do you bind data to a WPF control? 61 / 58