Загрузка данных


using System;
using System.IO;
using System.Linq;

class Program
{
    static void Main()
    {
        while (true)
        {
            Console.Clear();
            Console.WriteLine("=== Работа с файлами ===");
            Console.WriteLine("1. Прочитать файл и вывести построчно");
            Console.WriteLine("2. Записать строки в файл до ввода 'выход'");
            Console.WriteLine("3. Перезаписать файл (старое содержимое удаляется)");
            Console.WriteLine("4. Прочитать файл и записать строки в другой файл в обратном порядке");
            Console.WriteLine("5. Выход");
            Console.Write("Выберите действие: ");
            
            string choice = Console.ReadLine();
            if (choice == "5") break;

            switch (choice)
            {
                case "1":
                    ReadFileAndPrint();
                    break;
                case "2":
                    WriteLinesToFile();
                    break;
                case "3":
                    OverwriteFile();
                    break;
                case "4":
                    ReverseAndWriteToNewFile();
                    break;
                default:
                    Console.WriteLine("Неверный выбор. Нажмите любую клавишу...");
                    Console.ReadKey();
                    break;
            }
        }
    }

    // 1. Чтение файла и вывод построчно
    static void ReadFileAndPrint()
    {
        Console.Write("Введите путь к файлу: ");
        string path = Console.ReadLine();
        try
        {
            using (StreamReader reader = new StreamReader(path))
            {
                string line;
                Console.WriteLine("\nСодержимое файла:");
                while ((line = reader.ReadLine()) != null)
                    Console.WriteLine(line);
            }
        }
        catch (FileNotFoundException) { Console.WriteLine("Ошибка: Файл не найден."); }
        catch (DirectoryNotFoundException) { Console.WriteLine("Ошибка: Неверная директория."); }
        catch (UnauthorizedAccessException) { Console.WriteLine("Ошибка: Нет доступа."); }
        catch (Exception ex) { Console.WriteLine($"Ошибка: {ex.Message}"); }
        finally { Console.WriteLine("\nНажмите любую клавишу для продолжения..."); Console.ReadKey(); }
    }

    // 2. Запись строк в файл до ввода "выход"
    static void WriteLinesToFile()
    {
        Console.Write("Введите имя файла для записи: ");
        string path = Console.ReadLine();
        try
        {
            using (StreamWriter writer = new StreamWriter(path))
            {
                Console.WriteLine("Введите строки (для завершения введите 'выход'):");
                while (true)
                {
                    string input = Console.ReadLine();
                    if (input.ToLower() == "выход")
                        break;
                    writer.WriteLine(input);
                }
            }
            Console.WriteLine("Данные успешно записаны.");
        }
        catch (UnauthorizedAccessException) { Console.WriteLine("Ошибка: Нет прав для записи."); }
        catch (Exception ex) { Console.WriteLine($"Ошибка: {ex.Message}"); }
        finally { Console.WriteLine("\nНажмите любую клавишу для продолжения..."); Console.ReadKey(); }
    }

    // 3. Перезапись файла (удаление старого содержимого)
    static void OverwriteFile()
    {
        Console.Write("Введите путь к файлу для перезаписи: ");
        string path = Console.ReadLine();
        try
        {
            Console.WriteLine("Введите новый текст (для завершения введите пустую строку):");
            string newContent = "";
            string line;
            while ((line = Console.ReadLine()) != string.Empty)
                newContent += line + Environment.NewLine;

            File.WriteAllText(path, newContent);
            Console.WriteLine("Файл успешно перезаписан.");
        }
        catch (UnauthorizedAccessException) { Console.WriteLine("Ошибка: Нет прав для записи."); }
        catch (Exception ex) { Console.WriteLine($"Ошибка: {ex.Message}"); }
        finally { Console.WriteLine("\nНажмите любую клавишу для продолжения..."); Console.ReadKey(); }
    }

    // 4. Чтение файла и запись строк в обратном порядке в новый файл
    static void ReverseAndWriteToNewFile()
    {
        Console.Write("Введите путь исходного файла: ");
        string sourcePath = Console.ReadLine();
        Console.Write("Введите путь результирующего файла: ");
        string destPath = Console.ReadLine();
        try
        {
            string[] lines = File.ReadAllLines(sourcePath);
            Array.Reverse(lines);
            File.WriteAllLines(destPath, lines);
            Console.WriteLine("Файл успешно создан с перевёрнутым содержимым.");
        }
        catch (FileNotFoundException) { Console.WriteLine("Ошибка: Исходный файл не найден."); }
        catch (DirectoryNotFoundException) { Console.WriteLine("Ошибка: Неверный путь."); }
        catch (UnauthorizedAccessException) { Console.WriteLine("Ошибка: Нет доступа."); }
        catch (Exception ex) { Console.WriteLine($"Ошибка: {ex.Message}"); }
        finally { Console.WriteLine("\nНажмите любую клавишу для продолжения..."); Console.ReadKey(); }
    }
}