0% found this document useful (0 votes)
16 views

CH5-Manipulating Files in C#

Uploaded by

dekebagonji885
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

CH5-Manipulating Files in C#

Uploaded by

dekebagonji885
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Chapter Five

File system in C#

1
Read a file line by line
• The File class provides two static methods to read a text file in
C#.
• The File.ReadAllText() method opens a text file, reads all the text
in the file into a string, and then closes the file.
• The following code snippet reads a text file into a string.
// Read entire text file content in one string

string text = File.ReadAllText(textFile);


Console.WriteLine(text);

• The File.ReadAllLines() method opens a text file, reads all lines of


the file into a string array, and then closes the file.
• The following code snippet reads a text file into an array of
strings.
// Read a text file line by line.
string[] lines = File.ReadAllLines(textFile);
2
foreach (string line in lines)
Read a file …
• Read a text file is using a StreamReader class that implements a
TextReader and reads characters from a byte stream in a particular
encoding.
• The ReadLine method of StreamReader reads one line at a time.

// Read file using StreamReader. Reads file line by line


using(StreamReader file = new StreamReader(textFile)) {

string ln;

while ((ln = file.ReadLine()) != null) {


Console.WriteLine(ln);

}
file.Close();
Console.WriteLine($ "File has {counter} lines.");
}
3
Example ---sample code

using System;
using System.IO;

namespace ReadATextFile {
class Program {
// Default folder
static readonly string rootFolder = @ "C:\Temp\
Data\";
//
Default file. MAKE SURE TO CHANGE THIS LOCATION AND F
ILE PATH TO YOUR FILE
static readonly string textFile = @ "C:\Temp\Data\
Authors.txt";

4
Sample code …

static void Main(string[] args) {


if (File.Exists(textFile)) {
// Read entire text file content in one string
string text = File.ReadAllText(textFile);
Console.WriteLine(text);
}

if (File.Exists(textFile)) {
// Read a text file line by line.
string[] lines= File.ReadAllLines(textFile);
foreach(string line in lines) {
}
Console.WriteLine(line);

5
Sample code …

if (File.Exists(textFile)) {
// Read file using StreamReader. Reads file line by line
using(StreamReader file = new StreamReader(textFile)) {
int counter = 0;
string ln;
while ((ln = file.ReadLine()) != null) {
Console.WriteLine(ln);
counter++;
}
file.Close();
Console.WriteLine($ "File has {counter} lines.");
}
}
Console.ReadKey();
} } }
6
Sample code …

Assignment 1:
Given a text file, write a program that counts
the repeated words.
And also find the word with maximum repetition.
Example:
ocean: 3
water: 5
fish: 12

7
Write to a Text File

1. Write a collection of strings to a file

class WriteAllLines
{
public static async Task ExampleAsync()
{
string[] lines =
{
"First line", "Second line", "Third line“
};

await File.WriteAllLinesAsync("WriteLines.txt", lines);


}
}

• Instantiates a string array with three values.


• Awaits a call to File.WriteAllLinesAsync which:
• Asynchronously creates a file name WriteLines.txt. If the file already exists, it is
overwritten.
• Writes the given lines to the file.
• Closes the file, automatically flushing and disposing as needed. 8
2. Write one string to a file

class WriteAllText
{
public static async Task ExampleAsync()
{
string text =
"A class is the most powerful data type in C#. Like a structure, " +
"a class defines the data and behavior of the data type. ";

await File.WriteAllTextAsync("WriteText.txt", text);


}
}
• Instantiates a string given the assigned string literal.
• Awaits a call to File.WriteAllTextAsync which:
• Asynchronously creates a file name WriteText.txt. If the file already exists,
it is overwritten.
• Writes the given text to the file.
• Closes the file, automatically flushing and disposing as needed.

9
3. Write selected strings from an array to a file
class StreamWriterOne
{
public static async Task ExampleAsync()
{
string[] lines = { "First line", "Second line", "Third line" };
using StreamWriter file = new("WriteLines2.txt");

foreach (string line in lines)


{
if (!line.Contains("Second"))
{
await file.WriteLineAsync(line);
}
} }}
• Instantiates a string array with three values.
• Instantiates a StreamWriter with a file path of WriteLines2.txt as
a using declaration.
• Iterates through all the lines.
• Conditionally awaits a call to StreamWriter.WriteLineAsync(String),
which writes the line to the file when the line doesn't contain
“second”.

10
Append text to an existing file

class StreamWriterTwo
{
public static async Task ExampleAsync()
{
using StreamWriter file = new("WriteLines2.txt", append: true);
await file.WriteLineAsync("Fourth line");
}
}
• Instantiates a string array with three values.
• Instantiates a StreamWriter with a file path of WriteLines2.txt as
a using declaration, passing in true append.
• Awaits a call to StreamWriter.WriteLineAsync(String), which writes the string to the
file as an appended line.

11
How to copy, delete, and move files and folders

• The following examples show how to copy, move, and delete


files and folders in a synchronous manner by using the
System.IO.File, System.IO.Directory, System.IO.FileInfo, and
System.IO.DirectoryInfo classes from the System.IO
namespace

12
The following example shows how to copy files and directories.
public class SimpleFileCopy
{
static void Main()
{
string fileName = "test.txt";
string sourcePath = @"C:\Users\Public\TestFolder";
string targetPath = @"C:\Users\Public\TestFolder\SubDir";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.Directory.CreateDirectory(targetPath);
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
} }
else
{
Console.WriteLine("Source path does not exist!");
}
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}} 13
The following example shows how to move files and directories.

public class SimpleFileMove


{
static void Main()
{
string sourceFile = @"C:\Users\Public\public\test.txt";
string destinationFile = @"C:\Users\Public\private\test.txt";

// To move a file or folder to a new location:


System.IO.File.Move(sourceFile, destinationFile);

// To move an entire directory. To programmatically modify or combine


// path strings, use the System.IO.Path class.
System.IO.Directory.Move(@"C:\Users\Public\public\test\", @"C:\Users\Public\private");
}
}
14
The following example shows how to delete files and
directories.

public class SimpleFileDelete


{
static void Main()
{
// Delete a file by using File class static method...
if(System.IO.File.Exists(@"C:\Users\Public\DeleteTest\test.txt"))
{
// Use a try block to catch IOExceptions, to
// handle the case of the file already being
// opened by another process.
try
{
System.IO.File.Delete(@"C:\Users\Public\DeleteTest\test.txt");
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
return;
}
}
15
Delete …

System.IO.FileInfo fi = new System.IO.FileInfo(@"C:\Users\Public\DeleteTest\test2.txt");


try
{
fi.Delete();
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
try
{
System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest");
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
if(System.IO.Directory.Exists(@"C:\Users\Public\DeleteTest"))
{

16
Delete …

try
{
System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest", true);
}

catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
}

System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(@"C:\Users\Public\public");


try
{
di.Delete(true);
}
catch (System.IO.IOException e)
{
Console.WriteLine(e.Message);
}
}
}

17
Progress dialog box for file operations

• The following code copies the directory that sourcePath specifies into
the directory that destinationPath specifies.
• It also provides a standard dialog box that shows the estimated amount
of time remaining before the operation finishes as progress bar

Using Microsoft.VisualBasic.FileIO;
class FileProgress
{
static void Main()
{
string sourcePath = @"C:\Windows\symbols\";
string destinationPath = @"C:\TestFolder";

FileSystem.CopyDirectory(sourcePath, destinationPath,
UIOption.AllDialogs);
}
}

18

You might also like