Lecture No. 11
Dated: 21-05-2025
Extension Methods
using System;
using System.IO; // Required for File operations
namespace FileHandlingArticleApp {
class Program {
static void Main(string[] args) {
string filePath = "test.txt"; // Define the file path once for clarity
// Check if the file exists and display its current content
if (File.Exists(filePath)) {
string content = File.ReadAllText(filePath);
Console.WriteLine("Current content of file:");
Console.WriteLine(content);
}
Console.WriteLine("Please enter new content for the file - type 'exit' and press enter to finish editing:");
string newContent;
// Loop to continuously append new lines until the user types "exit"
while ((newContent = Console.ReadLine()) != "exit") { // Read user input and assign to newContent
// Append the new content followed by a new line to the file
File.AppendAllText(filePath, newContent + Environment.NewLine);
}
Console.WriteLine("File editing finished. Press any key to exit.");
Console.ReadKey(); // Keep the console window open
}
}
}
using System;
using System.IO; // Required for StreamWriter
class Program {
static void Main(string[] args) {
Console.WriteLine("Please enter new content for the file - type 'exit' and press enter to finish");
// Use a 'using' statement to ensure the StreamWriter is properly closed and disposed of,
// even if an error occurs. By default, StreamWriter will overwrite the file.
// If you want to append, you need to use: new StreamWriter("test.txt", true)
using (StreamWriter sw = new StreamWriter("test.txt")) {
string newContent = Console.ReadLine(); // Read the first line of input
while (newContent != "exit") {
sw.WriteLine(newContent); // Write the content and automatically add a newline
newContent = Console.ReadLine(); // Read the next line of input
}
}
Console.WriteLine("Content written to test.txt. Press any key to exit.");
Console.ReadKey(); // Keep the console window open
}
}
Deleting a File
using System;
using System.IO; // Required for StreamWriter
class Program {
static void Main(string[] args) {
Console.WriteLine("Please enter new content for the file - type 'exit' and press enter to finish");
// The 'using' statement ensures the StreamWriter is properly closed and disposed of,
// even if an error occurs.
// By default, `new StreamWriter("test.txt")` will **overwrite** the file if it exists.
// If you intend to **append** to the file, use `new StreamWriter("test.txt", true)`.
using (StreamWriter sw = new StreamWriter("test.txt")) {
string newContent = Console.ReadLine(); // Read the first line of input from the user
while (newContent != "exit") { // Continue reading until the user types "exit"
sw.WriteLine(newContent); // Write the user's input to the file, followed by a new line
newContent = Console.ReadLine(); // Read the next line of input
}
}
Console.WriteLine("Content successfully written to 'test.txt'.");
Console.WriteLine("Press any key to exit.");
Console.ReadKey(); // Keeps the console window open until a key is pressed
}
}
Rename a File
if (File.Exists("test.txt")) {
Console.WriteLine("Please enter a new name for this file:");
string newfilename = Console.ReadLine();
if (newfilename != string.Empty) {
File.Move("test.txt", newfilename);
if (File.Exists(newfilename)) {
Console.WriteLine("The file was renamed to " + newfilename);
Console.ReadKey();
}
}
}
Rename a Directory
if (Directory.Exists("testdir")) {
Console.WriteLine("Please enter a new name for this directory:");
string newdirname = Console.ReadLine();
if (newdirname != string.Empty) {
Directory.Move("testdir", newdirname);
if (Directory.Exists(newdirname)) {
Console.WriteLine("The directory was renamed to " + newdirname);
Console.ReadKey();
}
}
}
Create a Directory
Console.WriteLine("Please enter a name for the new directory:");
string newdirname = Console.ReadLine();
if (newdirname != string.Empty) {
Directory.CreateDirectory(newdirname);
if (Directory.Exists(newdirname)) {
Console.WriteLine("The directory was created!");
Console.ReadKey();
}
}
File Info Object
A file
info object gives you information about an object.
static void Main(string[] args) {
FileInfo fi = new FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
if (fi != null) {
Console.WriteLine(string.Format("Information about file: {0}, {1} bytes, last modified on {2}",
fi.Name, fi.Length, fi.LastWriteTime));
Console.ReadKey();
}
}
Directory Info Object
A directory
info object gives you information about a directory
.
DirectoryInfo di = new DirectoryInfo(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
if (di != null) {
FileInfo[] subfiles = di.GetFiles();
if (subfiles.Length > 0) {
Console.WriteLine("Files:");
foreach (FileInfo subfile in subfiles) {
Console.WriteLine("" + subfile.Name + " (" + subfile.Length + " bytes)");
}
}
Console.ReadKey();
}
Listing Subdirectories
DirectoryInfo[] subdirs = di.GetDirectories();
if (subdirs.Length > 0) {
Console.WriteLine("Directories:");
foreach (DirectoryInfo subdir in subdirs) {
Console.WriteLine("" + subdir.Name);
}
}
Example
We will now build a complete profile save load system with reflection
.
using System;
using System.IO;
using System.Reflection;
class Program {
public class Person {
public void Load() {
if (File.Exists("settings.dat")) {
Type type = this.GetType();
string propertyname, value;
string[] temp;
char[] splitchars = new char[] { '|' };
PropertyInfo propertyinfo;
string[] settings = File.ReadAllLines("settings.dat");
foreach (string s in settings) {
temp = s.Split(splitchars);
if (temp.Length == 2) {
propertyname = temp[0];
value = temp[1];
propertyinfo = type.GetProperty(propertyname);
if (propertyinfo != null)
this.SetProperty(propertyinfo, value);
}
}
}
}
public void Save() {
Type type = this.GetType();
PropertyInfo[] properties = type.GetProperties();
TextWriter tw = new StreamWriter("settings.dat");
foreach (PropertyInfo propertyinfo in properties)
tw.WriteLine(propertyinfo.Name + "|" + propertyinfo.GetValue(this, null));
tw.Close();
}
public void SetProperty(PropertyInfo propertyinfo, object value) {
switch (propertyinfo.PropertyType.Name) {
case "Int32":
propertyinfo.SetValue(this, Convert.ToInt32(value), null);
break;
case "String":
propertyinfo.SetValue(this, value.ToString(), null);
break;
}
}
public int Age { get; set; }
public string Name { get; set; }
}
static void Main(string[] args) {
Person person = new Person();
person.Load();
if ((person.Age > 0) && (person.Name != string.Empty)) {
Console.WriteLine("Hi " + person.Name + " - you are " + person.Age + " years old!");
} else {
Console.WriteLine("I don't seem to know much about you. Please enter the following information:");
Type type = typeof(Person);
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo propertyinfo in properties) {
Console.WriteLine(propertyinfo.Name + ":");
person.SetProperty(propertyinfo, Console.ReadLine());
}
person.Save();
Console.WriteLine("Thank you! I have saved your information for next time.");
}
Console.ReadKey();
}
}