“Dasturlash asoslari” fanidan “C# dasturlash tilining Directory, DirectoryInfo va DriveInfo sinflari hamda ular bilan ishlash”


II BOB. C# DASTURLASH TILINING DIRECTORYINFO SINFI VA U BILAN ISHLASH


Download 0.63 Mb.
bet5/6
Sana12.11.2020
Hajmi0.63 Mb.
#144473
1   2   3   4   5   6
Bog'liq
kurs ishi

II BOB. C# DASTURLASH TILINING DIRECTORYINFO SINFI VA U BILAN ISHLASH

2.1 DirectoryInfo sinfidan foydalanish


DirectoryInfo sinfi kataloglar bilan ishlashning namunaviy usullarini taqdim etadi. DirectoryInfo sinfi katalog haqida ma'lumot beradi, uni DirectoryInfo ob'ektini yaratishda konstruktor orqali joylash mumkin. Fayl tizimidagi katalog bilan bog'langan DirectoryInfo ob'ekti qo’lga kiritilgach, biz har qanday ma'lumotni, shu jumladan tarkibidagi fayllarni ham olishimiz mumkin. FileInfo sinfi singari, DirectoryInfo sinfi ham kirish parametr sifatida katalogga to'liq yo'lni yoki nisbiy yo'lni oladigan yagona konstruktorga ega:

DirectoryInfo d1 = new DirectoryInfo(@"c:\temp"); // Katalog ob'ekti yaratish

DirectoryInfo sinfining ba'zi muhim xususiyatlari, masalan, CreationTime, Exists, FullName, LastAccessTime, LastWriteTime, Parent, Name va Root, bular nomlaridan kelib chiqib ishlaydi. Masalan, CreationTime katalogni yaratilish vaqtini ko'rsatadi. FullName esa katalogning to'liq yetarli yo'li, Name esa shunchaki nisbiy papkaning nomi bo'lib, yo'l yo'q (masalan, to'liq nomi c:\Mening loyiham\test bo'lgan katalogning nomi test bo'ladi). Ma’lumot turi System.IO.FileSystemInfo dan meros bo'lib o'tgan, shuning uchun u ona sinfning juda ko'p yuklangan metodlari, shuningdek kataloglar bilan ishlashda o'nlab foydali xususiyatlarga ega:


  • Attributesdan foydalanib, masalan, katalogning atributlarini o'qish yoki so'rash mumkin;

  • Extension – katalog ichidagi fayl kengaytmalari haqida ma'lumot beradi;

  • Exists katalog mavjudligini tekshiradi;

  • Name, Parent, Root – katalog nomini, ona yoki ildiz katalogiga yo'lni qaytaradi.

  • FullName – katalogning to’liq yo’lini qaytaradi.

DirectoryInfo ma’lumot turi (sinfi) bo'lganligi sababli, uning a'zolaridan foydalanishdan oldin, ob'ektni konstruktor yordamida yaratish kerak. Konstruktor parametri sifatida katalog nomi va yo'lini satrda uzatish kerak. Katalogga yaratilgan DirectoryInfo nusxasi joriy ishchi katalog sifatida tayinlanadi.

DirectoryInfo firstDir = new DirectoryInfo(@"C:\Temp");


DirectoryInfo secondDir = new DirectoryInfo(".");

Konstruktor kataloglarni yaratmaydi, faqat ularni bog'laydi. Agar konstruktorga boradigan yo'l bilan birga yuborilgan katalog mavjud bo'lmasa, uni ishlatishdan oldin Create() metodidan foydalanib yaratish kerak, aks holda undan foydalanish istisnolarni keltirib chiqaradi.

DirectoryInfo firstDir = new DirectoryInfo(@"C:\Temp");
firstDir.Create();

Ob'ektni try/catch blokida ishlatishdan oldin Exist xususiyatidan foydalanish afzalroq:



Foydalanish misoli:

using System;
using System.IO;
namespace dir
{
    class Program
    {
        public static void Main(string[] args)
        {
            DirectoryInfo firstDir = new DirectoryInfo(@"C:\Temp");
        try 
        {
              if (firstDir.Exists) 
            {
                Console.WriteLine("Bu yo'l allaqachon mavjud.");
                return;
            }
            // Katalog yaratish
            firstDir.Create();
            Console.WriteLine("Katalog muvaffaqiyatli yaratildi.");
            // Endi o'chirish
            firstDir.Delete();
            Console.WriteLine("Katalog muvaffaqiyatli o'chirildi.");
        } 
        catch (Exception e) 
        {
            Console.WriteLine("Jarayon to’xtatildi: {0}", e.ToString());
        } 
            Console.ReadKey(true);
        }
    }
}

Natijasi:

DirectoryInfo sinfining maqsadi Directory bilan bir xil. Biroq, DirectoryInfo bir xil ob'ekt (katalog) ko'p ishlatiladigan operatsiyalar uchun ishlatiladi. Qaytadan ro'yxatdan o'tkazmaslik uchun tekshirishni boshlashning har bir bosqichida ob'ekt havolasidan foydalanish qulayroqdir.


2.2 DirectoryInfo sinfining metodlari va ular bilan ishlash


Create() – ­­­­­­yangi katalog yaratadi.

Foydalanish misoli:

using System;
using System.IO;
class Programm 
{
    public static void Main() 
    {
       DirectoryInfo di = new DirectoryInfo(@"C:\MyDir");
        try 
        {
            if (di.Exists) 
            {
              Console.WriteLine("Bu yo'l allaqachon mavjud.");
                return;
            }
            di.Create();
            Console.WriteLine("Katalog muvaffaqiyatli yaratildi.");
            di.Delete();
            Console.WriteLine("Katalog muvaffaqiyatli o'chirildi.");
        } 
        catch (Exception e) 
        {
            Console.WriteLine("Jarayon to’xtatildi: {0}", e.ToString());
        } 
        finally {}
        Console.ReadKey();
    }
}

Natijasi:

CreateSubdirectory(String) – belgilangan yo'lda pastki katalog yoki pastki kataloglar yaratadi. Belgilangan yo'l DirectoryInfo sinfining ushbu namunasi bilan o’zaro bog’liq bo'lishi mumkin.



Foydalanish misoli:

using System;
using System.IO;
namespace Dir
{
    class Program
    {
        public static void Main(string[] args)
        {
        DirectoryInfo di = new DirectoryInfo(@"C:\TempDir");
         if (di.Exists == false)
          di.Create();
           Console.WriteLine("Katalog muvafaqqiyatli yaratildi.");
           DirectoryInfo dis = di.CreateSubdirectory("SubDir");
           Console.WriteLine("Pastki katalog muvafaqqiyatli yaratildi.");
           dis.Delete(true);
          Console.WriteLine("Pastki katalog muvaffaqiyatli o'chirildi.");
           di.Delete(true);
           Console.WriteLine("Katalog muvaffaqiyatli o'chirildi.");
           Console.ReadKey();
        }
    }
}

Natijasi:

Delete() – agar u bo'sh bo'lsa, bu DirectoryInfo ni yo'q qiladi.



Foydalanish misoli:

using System;
using System.IO;
class Test 
{
    public static void Main() 
    {
         DirectoryInfo di1 = new DirectoryInfo(@"C:\MyDir");
        try 
        {
            di1.Create();
            di1.CreateSubdirectory("temp");
            Console.WriteLine("Men {0}ni o'chirishga harakat qilyapman.", di1.Name);
            di1.Delete();
            Console.WriteLine("Yo'q qilish operatsiyasi tasodifan muvafaqqiyatli yuz berdi.");
        } 
        catch (Exception) 
        {
            Console.WriteLine("Yo'q qilish operatsiyasi kutilganidek muvafaqqiyatsiz yuz berdi.");
        } 
        finally {}
        Console.ReadKey();
    }
}

Natijasi:

Delete(Boolean) – pastki kataloglar va fayllarni yo'q qilish kerakligini aniqlab, DirectoryInfo ning ushbu nusxasini yo'q qiladi.



Foydalanish misoli:

          DirectoryInfo di = new DirectoryInfo(@"C:\TempDir");


         if (di.Exists == false)
          di.Create();
          DirectoryInfo dis = di.CreateSubdirectory("SubDir");
          Console.WriteLine("Katalog va pastki katalog muvafaqqiyatli yaratildi.");
          //True shuni ko'rsatadiki, agar ushbu katalogda pastki kataloglar
          // yoki fayllar bo'lsa, ular ham o'chiriladi.
          di.Delete(true);
          Console.WriteLine("Katalog va pastki katalog muvafaqqiyatli o'chirildi.");
          Console.ReadKey();
Natijasi:

GetDirectories() – belgilangan katalogdagi pastki kataloglarning nomlarini (shu jumladan yo’llarini) qaytaradi.



Foydalanish misoli:

using System;
using System.IO;
public class GetDirectoriesTest 
{
    public static void Main() 
    {
        DirectoryInfo di = new DirectoryInfo("C:\\");
        DirectoryInfo[] diArr = di.GetDirectories();
        Console.Write("    'C:\\' diskdagi kataloglar:");
        Console.WriteLine();
        foreach (DirectoryInfo dri in diArr)
            Console.WriteLine("\t" +dri.Name);
        Console.ReadKey();
    }
}

Natijasi:

GetDirectories(String) – belgilangan katalogdagi qidiruv uslubiga mos keladigan pastki kataloglarning nomlarini (shu jumladan yo’llarini) qaytaradi.



GetDirectories(String, SearchOption) – belgilangan katalogdagi belgilangan qidiruv namunasiga mos keladigan pastki kataloglarning nomlarini (shu jumladan yo’llarini) va ixtiyoriy ravishda pastki kataloglarni qaytaradi.

Foydalanish misoli:

using System;
using System.IO;
public class GetDirectoriesTest 
{
    public static void Main() 
    {
        DirectoryInfo di = new DirectoryInfo("C:\\");
        DirectoryInfo[] diArr = di.GetDirectories("p*");   //("p*", SearchOption.TopDirectoryOnly)
        Console.Write("  'C:\\' diskdagi 'p' harfi bilan boshlanuvchi kataloglar:");
        Console.WriteLine();
        foreach (DirectoryInfo dri in diArr)
            Console.WriteLine("\t" +dri.Name);
        Console.ReadKey();
    }
}

Natijasi:

EnumerateDirectories() – joriy katalogdagi ma'lumotlarni sanaydigan to'plamni qaytaradi.



Foydalanish misoli:

using System;
using System.IO;
using System.Linq;
namespace EnumDir
{
    class Program
    {
        static void Main(string[] args)
        {
            string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            DirectoryInfo dirPrograms = new DirectoryInfo(docPath);
            DateTime StartOf2019 = new DateTime(2019, 12, 04);
            var dirs = from dir in dirPrograms.EnumerateDirectories()
            where dir.CreationTimeUtc > StartOf2019
            select new
            {
                ProgDir = dir,
            };
            Console.WriteLine("(2019, 12, 04) sanadan boshlab yaratilgan kataloglar ro'yxati:"+"\n");
            foreach (var di in dirs)
            {
                Console.WriteLine(di.ProgDir.Name);
            }
              Console.ReadKey();
            }
     }
}

Natijasi:

EnumerateDirectories(String) – belgilangan yo’lda qidirish namunasiga mos keladigan katalogning to’liq nomlarini sanaydigan to’plamni qaytaradi.



Foydalanish misoli:

Public System.Collections.Generic.IEnumerable

EnumerateDirectories (string searchPattern);

EnumerateDirectories(String, SearchOption) – belgilangan yo’lda qidirish namunasiga mos keladigan katalogning to’liq nomlarini sanaydigan to’plamini va ixtiyoriy ravishda qidirilgan pastki kataloglarni qaytaradi.



Foydalanish misoli:

public System.Collections.Generic.IEnumerable

EnumerateDirectories (string searchPattern, SearchOption searchOption);

MoveTo() – DirectoryInfo nusxasini va uning tarkibini yangi yo'lga ko'chiradi.



Foydalanish misoli:

using System;
using System.IO;
public class MoveToTest 
{
    public static void Main() 
    {
        string oldPath = @"C:\SomeFolder";
        string newPath = @"C:\SomeDir";
        DirectoryInfo dirInfo = new DirectoryInfo(oldPath);
        if (dirInfo.Exists && Directory.Exists(newPath) == false)
        {
            dirInfo.MoveTo(newPath);
            Console.WriteLine("Katalog muvaffaqiyatli ko'chirildi.");
        }
        Console.ReadKey();
    }
}

Natijasi:



Download 0.63 Mb.

Do'stlaringiz bilan baham:
1   2   3   4   5   6




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling