The following example shows how to retrieve all the text files from a directory and move them to a new directory. After the files are moved, they no longer exist in the original directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.IO; namespace ConsoleApplication { class Program { static void Main(string[] args) { string sourceDirectory = @"C:\current"; string archiveDirectory = @"C:\archive"; try { var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt"); foreach (string currentFile in txtFiles) { string fileName = currentFile.Substring(sourceDirectory.Length + 1); Directory.Move(currentFile, Path.Combine(archiveDirectory, fileName)); } } catch (Exception e) { Console.WriteLine(e.Message); } } } } |
The following example demonstrates how to use the M:System.IO.Directory.EnumerateFiles(System.String) method to retrieve a collection of text files from a directory, and then use that collection in a query to find all the lines that contain “Example”.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.IO; using System.Linq; namespace ConsoleApplication { class Program { static void Main(string[] args) { string archiveDirectory = @"C:\archive"; var files = from retrievedFile in Directory.EnumerateFiles(archiveDirectory, "*.txt", SearchOption.AllDirectories) from line in File.ReadLines(retrievedFile) where line.Contains("Example") select new { File = retrievedFile, Line = line }; foreach (var f in files) { Console.WriteLine("{0} contains {1}", f.File, f.Line); } Console.WriteLine("{0} lines found.", files.Count().ToString()); } } } |
The following example demonstrates how to move a directory and all its files to a new directory. The original directory no longer exists after it has been moved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.IO; namespace ConsoleApplication { class Program { static void Main(string[] args) { string sourceDirectory = @"C:\source"; string destinationDirectory = @"C:\destination"; try { Directory.Move(sourceDirectory, destinationDirectory); } catch (Exception e) { Console.WriteLine(e.Message); } } } } |