FILE AND DIRECTORY MANAGEMENT
Here are some file and directory classes commonly used in file and directory management in c sharp:
- File provides static methods for creating, copying, deleting, moving, and opening files.
- FileInfo – Provides instance methods for creating, copying, deleting, moving, and opening files.
- Directory allows you to use static methods for creating, moving, and enumerating directories and subdirectories.
- DirectoryInfo allows you to use instance methods for creating, moving, and enumerating directories and subdirectories.
- Path – Provides methods and properties that allow you to process directory strings regardless of platform.
FILES AND DIRECTORIES IN C SHARP THE STREAMS
The Stream abstract base class supports reading and writing bytes. All classes representing streams inherit from the Stream class. The Stream class and its derived classes provide a common representation of archives and data sources, thus separating the programmer from specific details of the operating system and underlying devices.
Flows involve three fundamental operations:
- Read: Transfer of data from a stream to a data structure, such as a byte array.
- Write: Transferring data from a data source to a stream.
- Search: query of a stream and modification of the current position within it.
Here are some commonly used flow classes:
- FileStream: for reading and writing to a file.
- MemoryStream: for reading and writing to memory as the backup archive.
- BufferedStream: to improve the performance of read and write operations.
- NetworkStream: for reading and writing on network sockets.
FILE AND DIRECTORY IN C SHARP READER AND WRITER
The System.IO namespace also provides types for reading encoded characters from streams and for writing them to streams. Streams are typically designed for byte input and output. The reader and writer types handle the conversion of encoded characters to bytes and vice versa, so that the stream can complete the operation. Each reader and writer class is associated with a stream, which can be retrieved through the class’s BaseStream property.
Here are some commonly used classes of readers and writers:
- BinaryReader and BinaryWriter: For reading and writing primitive data types, such as binary values.
- StreamReader and StreamWriter: For reading and writing characters using an encoding value for converting characters to bytes and vice versa.
- StringReader and StringWriter: for reading and writing characters from strings and vice versa.
- TextReader and TextWriter – serve as abstract base classes for other readers and writers that read and write characters and strings, but not binary data.
READING AND WRITING A TEXT FILE
using System; using System.IO; using System.Threading.Tasks; namespace FileDirectory { class Program { static async Task Main(string[] args) { String file = await ReadWriteText(); Console.WriteLine(file); } //READING AND WRITING A TEXT FILE private static async Task<string>; ReadWriteText() { string buffer; string output = null; try { using(StreamReader reader = File.OpenText(@"C:\Temp\input.txt")) { using(StreamWriter writer = File.CreateText(@"C:\Temp\output.txt")) { while((buffer = await reader.ReadLineAsync())!=null) { writer.WriteLine(buffer); output += buffer; } } return output; } } catch(Exception ex) { Console.WriteLine(ex.Message); return null; } } } }
LIST OF FILES IN A DIRECTORY
using System; using System.IO; using System.Threading.Tasks; namespace FileDirectory { class Program { static void Main(string[] args) { GetDirectoryFiles(); } //LIST OF FILES IN A DIRECTORY private static void GetDirectoryFiles() { string path = @"C:\Temp"; try { DirectoryInfo directory = new DirectoryInfo(path); FileInfo[] files = directory.GetFiles("*.txt"); foreach(var item in files) Console.WriteLine(item); } catch(Exception e) { Console.WriteLine(e.Message); return; } } } }
COPY A DIRECTORY
using System.IO; using System.Threading.Tasks; namespace FileDirectory { class Program { static void Main(string[] args) { CopyDirectory(); } //COPY A DIRECTORY private static void CopyDirectory() { DirectoryInfo source = new DirectoryInfo(@"C:\Temp2"); DirectoryInfo destination = new DirectoryInfo(@"C:\Temp3"); CopyDirectory(source,destination); } static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination) { if (!destination.Exists) { destination.Create(); } // Copy all files FileInfo[] files = source.GetFiles(); foreach (var file in files) file.CopyTo(Path.Combine(destination.FullName,file.Name)); // Process subdirectories DirectoryInfo[] dirs = source.GetDirectories(); foreach (DirectoryInfo dir in dirs) { // Destination directory //Path.Combine combines two strings into one pah. string destinationDir = Path.Combine(destination.FullName, dir.Name); // Call the function itself recursively CopyDirectory(dir, new DirectoryInfo(destinationDir)); } } } }
WRITE AND READ A BINARY FILE
using System; using System.IO; using System.Threading.Tasks; namespace FileDirectory { class Program { static async Task Main(string[] args) { await ReadWriteBinaryFile(); } //WRITE AND READ A BINARY FILE private static async Task ReadWriteBinaryFile() { byte[] output = new byte[] {0x66, 0x67, 0x68, 0x69, 0x70,0x71,0x72, 0x73, 0x74, 0x75, 0x76,0x77}; try { if(File.Exists(@"C:\Temp\outputbinary.txt")) File.Delete(@"C:\Temp\outputbinary.txt"); //WRITE using(FileStream stream = new FileStream(@"C:\Temp\outputbinary.txt",FileMode.Create)) { await stream.WriteAsync(output,0,output.Length); } //READ using(FileStream stream = new FileStream(@"C:\Temp\outputbinary.txt",FileMode.Open)) { int count = 0; int read; byte[] buffer = new byte[output.Length]; while (count < output.Length) { read = await stream.ReadAsync(buffer, 0, output.Length); Console.Write(Convert.ToChar(buffer.GetValue(count)) + " "); count++; } } } catch(Exception e) { Console.WriteLine(e.Message); } } } }
DEEPENING
In C#, working with files and directories is a common operation, and the .NET platform provides several classes to facilitate these operations, such as File, Directory, FileInfo, and DirectoryInfo. Below I will provide a detailed explanation of how to use these classes.
Main Classes for File and Directory Management.
1. File Class: Provides static methods for creating, copying, deleting, moving, and opening files. It also allows you to read and write directly to files.
2. Directory Class: Provides static methods for creating, deleting, and moving directories. It also allows obtaining information about directories and their contents.
3. FileInfo Class: Provides properties and instance methods for manipulating files. Unlike the File class, this class must be instantiated.
4. DirectoryInfo class: Provides properties and instance methods for manipulating directories. Like FileInfo, this must also be instantiated.
Operations with the File Class.
Here are some examples of common operations using the File class.
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = @”C:\example\myfile.txt“;
// Creare un file e scrivere del testo
File.WriteAllText(filePath, “Hello, world!“);
// Leggere il contenuto di un file
string content = File.ReadAllText(filePath);
Console.WriteLine(content);
// Copiare un file
string copyPath = @”C:\example\myfile_copy.txt“;
File.Copy(filePath, copyPath);
// Eliminare un file
File.Delete(copyPath);
}
}
Operations with the Directory Class
Here are some examples of common operations using the Directory class.
using System;
using System.IO;
class Program
{
static void Main()
{
string dirPath = @”C:\example\mydir“;
// Creare una directory
Directory.CreateDirectory(dirPath);
// Verificare se una directory esiste
if (Directory.Exists(dirPath))
{
Console.WriteLine(“La directory esiste.“);
}
// Ottenere i file in una directory
string[] files = Directory.GetFiles(dirPath);
foreach (string file in files)
{
Console.WriteLine(file);
}
// Eliminare una directory
Directory.Delete(dirPath, true); // Il parametro true elimina anche il contenuto della directory
}
}
Using FileInfo and DirectoryInfo.
The FileInfo and DirectoryInfo classes offer methods similar to the static File and Directory classes, but can be used for object-oriented operations.
using System;
using System.IO;
class Program
{
static void Main()
{
// Utilizzo di FileInfo
FileInfo fileInfo = new FileInfo(@”C:\example\myfile.txt“);
fileInfo.Create().Close(); // Creare un file
fileInfo.WriteAllText(“Hello, world!”); // Scrivere testo nel file
Console.WriteLine(fileInfo.Length); // Ottenere la dimensione del file
// Utilizzo di DirectoryInfo
DirectoryInfo dirInfo = new DirectoryInfo(@”C:\example\mydir“);
dirInfo.Create(); // Creare una directory
Console.WriteLine(dirInfo.FullName); // Ottenere il percorso completo della directory
dirInfo.Delete(true); // Eliminare la directory e il suo contenuto
}
}
Important Notes.
– When working with files and directories, it is important to handle exceptions to avoid runtime errors. For example, if you try to read a file that does not exist, you will get a FileNotFoundException.
– Always use properly formatted absolute or relative paths to avoid errors.
– Pay attention to file and directory permissions, especially when performing write or delete operations.
Leave A Comment