C# Directories


This entry is part 4 of 4 in the series C# Files Directories

Working with files and directories is perhaps one of the easier things to do in C#. Because files are used for input an output the file classes are contained in the System.IO directory. There are few classes we will likely be working with, File, FileInfo, Directory, DirectoryInfo and Path. The namespace System.IO has these classes, so you need to add using.

There are many more examples of these classes at MSDN online.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;                 // add this
namespace Directories
{
    class Program
    {
        static void Main(string[] args)
        {
            Directory.CreateDirectory(@"D:\temp\folder1");
            File.Create(@"D:\temp\folder1\mytext.txt");
            string[] files = Directory.GetFiles(@"D:\temp\folder1", "*.*", SearchOption.AllDirectories);

            foreach (var file in files){
                Console.WriteLine(file);
            }

            var directories = Directory.GetDirectories(@"D:\temp","*.*", SearchOption.AllDirectories);
            foreach (var dir in directories)
            {
                Console.WriteLine(dir);
            }

            var directoryInfo = new DirectoryInfo(...);
                directoryInfo.GetFiles();
                directoryInfo.GetDirectories();

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();

        }
    }
}
Series Navigation<< C# Filestream