Saturday 10 March 2012

To Access files and folders in C#


// To access files and folders of computer
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
DirectoryInfo d = new DirectoryInfo(@"D:\myPhotos");

//To Print All Folders
        Console.WriteLine("-------------Folders-------------");
        foreach (DirectoryInfo di in d.GetDirectories())
        {
Console.WriteLine(di.Name);
        }

//To Print All Files
        Console.WriteLine("-------------Files-------------");
        foreach (FileInfo di in d.GetFiles())
        {
Console.WriteLine(di.Name);
        }

// To Create a directory
DirectoryInfo d1 = new DirectoryInfo(@"D:\myPhotos\Ankur");
        d1.Create();


//To Create, Copy and Move files
//--------------First Method---------------
        //File.CreateText(@"D:\myPhotos\Ankur.txt");
        //File.Copy(@"D:\myPhotos\Ankur.txt", @"D:\myPhotos\Ankur1.txt");
        //File.Move(@"D:\myPhotos\Ankur.txt", @"D:\myPhotos\Ankur2.txt");
//File.Delete(@"D:\myPhotos\Ankur.txt");

//--------------Second Method---------------
FileInfo fi = new FileInfo(@"D:\myPhotos\Ankur.txt");
         //fi.Create();
         //fi.CopyTo(@"D:\myPhotos\Ankur1.txt");
         fi.MoveTo(@"D:\myPhotos\Ankur2.txt");
         fi.Delete();

        Console.ReadLine();
    }
}

No comments:

Post a Comment