CH5-Manipulating Files in C#
CH5-Manipulating Files in C#
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 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 …
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
class WriteAllLines
{
public static async Task ExampleAsync()
{
string[] lines =
{
"First line", "Second line", "Third line“
};
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. ";
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");
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
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.
16
Delete …
try
{
System.IO.Directory.Delete(@"C:\Users\Public\DeleteTest", 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