Dastur O'zini Qo'llash: Dasturda bir xato yuzaga kelsa, dastur yozuvini log fayliga yozing. Log fayli topilmagan yoki yozib bo'lmay qolsa, dastur to'xtasin va xatolik haqida ma'lumot chiqarsin. (Exception va boshqa obyektlar orqali).
using System;
using System.IO;
class Program
{
static void Main()
{
try
{
Console.WriteLine("Fayl nomini kiriting:");
string fileName = Console.ReadLine();
// Fayl nomi bilan log faylini yaratamiz
string logFileName = "log.txt";
using (StreamWriter logWriter = new StreamWriter(logFileName, true))
{
logWriter.WriteLine($"Dastur ishga tushdi: {DateTime.Now}");
// Faylni o'qish uchun FileStream yaratamiz
using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
{
// Faylni o'qish uchun StreamReader yaratamiz
using (StreamReader reader = new StreamReader(fileStream))
{
// Fayl ichidagi matnni o'qib konsolga chiqaramiz
string content = reader.ReadToEnd();
Console.WriteLine("Fayl matni:\n" + content);
}
}
}
}
catch (FileNotFoundException ex)
{
Console.WriteLine($"Xato: {ex.Message}");
LogError(ex);
}
catch (IOException ex)
{
Console.WriteLine($"IOException xato: {ex.Message}");
LogError(ex);
}
catch (Exception ex)
{
Console.WriteLine($"Umumiy xato: {ex.Message}");
LogError(ex);
}
finally
{
Console.WriteLine("Finally blok ishga tushdi.");
}
}
static void LogError(Exception ex)
{
// Log fayliga xatoni yozamiz
using (StreamWriter logWriter = new StreamWriter("log.txt", true))
{
logWriter.WriteLine($"Xato: {ex.Message}");
logWriter.WriteLine($"Stack Trace: {ex.StackTrace}");
logWriter.WriteLine("----------------------------------------");
}
}
}
Fayl yozish: Dastur yozing, foydalanuvchi tomonidan kiritilgan matnni bir faylga yozsin. Agar fayl topilmagan yoki yozib bo'lmay qolsa, dastur to'xtasin va xatolik haqida ma'lumot chiqarsin. (IOException va boshqa obyektlar orqali).
using System;
using System.IO;
class Program
{
static void Main()
{
try
{
Console.WriteLine("Fayl nomini kiriting:");
string fileName = Console.ReadLine();
Console.WriteLine("Matnni kiriting:");
string content = Console.ReadLine();
// Fayl nomi bilan StreamWriter yaratamiz
using (StreamWriter writer = new StreamWriter(fileName, true))
{
// Matnni faylga yozamiz
writer.WriteLine(content);
Console.WriteLine("Matn faylga muvaffaqiyatli yozildi.");
}
}
catch (IOException ex)
{
Console.WriteLine($"IOException xato: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"Umumiy xato: {ex.Message}");
}
finally
{
Console.WriteLine("Finally blok ishga tushdi.");
}
}
}
Dostları ilə paylaş: |