Harry Potter and the Sorcerer's Stone


C# yordamida katalogdan rekursiv nusxa oling


Download 192.49 Kb.
bet44/62
Sana17.06.2023
Hajmi192.49 Kb.
#1535967
1   ...   40   41   42   43   44   45   46   47   ...   62
Bog'liq
Algaritim amaliy-2

35. C# yordamida katalogdan rekursiv nusxa oling.
Javob:
Siz DirectoryInfo va FileInfo sinflaridan C# da katalog va uning mazmunini rekursiv nusxalash uchun foydalanishingiz mumkin.
using System.IO;
// create a DirectoryInfo object for the source directory
DirectoryInfo sourceDir = new DirectoryInfo("source_directory");
// create a DirectoryInfo object for the target directory
DirectoryInfo targetDir = new DirectoryInfo("target_directory");
// call the recursive copy method on the source directory
CopyDirectory(sourceDir, targetDir);
// define the recursive copy method
void CopyDirectory(DirectoryInfo source, DirectoryInfo target)
{
// create the target directory if it doesn't exist
if (!target.Exists)
{
target.Create();
}

// copy all the files in the source directory to the target directory


foreach (FileInfo file in source.GetFiles())
{
string targetPath = Path.Combine(target.FullName, file.Name);
file.CopyTo(targetPath, true);
}

// copy all the directories in the source directory recursively


foreach (DirectoryInfo subdir in source.GetDirectories())
{
string targetPath = Path.Combine(target.FullName, subdir.Name);
CopyDirectory(subdir, new DirectoryInfo(targetPath));
}
}
Ushbu kod kirish argumentlari sifatida manba DirectoryInfo ob'ektini va maqsadli DirectoryInfo ob'ektini oladigan CopyDirectory() usulini belgilaydi. Bu maqsadli katalog mavjudligini tekshirish va kerak bo'lganda uni yaratish bilan boshlanadi. Keyin u manba katalogidagi barcha fayllarni aylanib chiqadi va ularni CopyTo() usuli yordamida maqsadli katalogga nusxalaydi. Nihoyat, u manba katalogidagi barcha quyi kataloglar boʻylab aylanib chiqadi va ularni va ularning mazmunini nusxalash uchun CopyDirectory() usulini rekursiv chaqiradi.
36. C# yordamida katalogni rekursiv tarzda o'chiring.
Javob:
C# yordamida katalogni rekursiv yoʻq qilish uchun siz Directory.Delete() usulini true parametri bilan ishlatishingiz mumkin:
string directoryPath = @"C:\DirectoryPath\";
Directory.Delete(directoryPath, true);
Bu katalog va uning barcha tarkibini rekursiv ravishda oʻchirib tashlaydi. Katalogni oʻchirishdan oldin kerakli ruxsatlarga ega ekanligingizga ishonch hosil qiling.

Download 192.49 Kb.

Do'stlaringiz bilan baham:
1   ...   40   41   42   43   44   45   46   47   ...   62




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