0

Моя программа генерации паролей должна записывать каждый созданый пароль в текстовый файл.

Вроде все правильно сделано, но возникает ошибка Cannot write to a closed TextWriter.ObjectDisposed_ObjectName_Name - не совсем понимаю причину.

StreamWriter sw = new StreamWriter("C:\\Users\\" + username +"\\Downloads\\passwords.txt"); - я создаю StreamWriter который записывает путь, затём в цикле создания пароля, я вставляю функцию записи в файл, по идеи:

  1. Генерируется пароль в цикле
  2. Идёт проверка стоит ли true на запись в файл - если да то записать - и закрыть поток.

но возникает ошибка.

EDIT: Попробовал добавить sw.Flush(); но не помогло.

for (int a = 0; a < colvo; a++)
                {
                    string password = GeneratePassword(dictionary, length);
                    if (save5 == true)
                    {
                        sw.WriteLine(password);
                        sw.Close();
                    }
                    Console.WriteLine(password);
                }
                Console.ReadKey();

Что не так?

Весь код:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Principal;


namespace PGC_by_Zekoyka
{

    class Program
    {
        private const int MF_BYCOMMAND = 0x00000000;
        public const int SC_CLOSE = 0xF060;
        public const int SC_MINIMIZE = 0xF020;
        public const int SC_MAXIMIZE = 0xF030;
        public const int SC_SIZE = 0xF000;

        [DllImport("user32.dll")]
        public static extern int DeleteMenu(IntPtr hMenu, int nPosition, int wFlags);

        [DllImport("user32.dll")]
        private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);

        [DllImport("kernel32.dll", ExactSpelling = true)]
        private static extern IntPtr GetConsoleWindow();

        static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
        static readonly IntPtr HWND_TOP = new IntPtr(0);
        const UInt32 SWP_NOSIZE = 0x0001;
        const UInt32 SWP_NOMOVE = 0x0002;
        const UInt32 SWP_NOZORDER = 0x0004;
        const UInt32 SWP_NOREDRAW = 0x0008;
        const UInt32 SWP_NOACTIVATE = 0x0010;
        const UInt32 SWP_FRAMECHANGED = 0x0020;
        const UInt32 SWP_SHOWWINDOW = 0x0040;
        const UInt32 SWP_HIDEWINDOW = 0x0080;
        const UInt32 SWP_NOCOPYBITS = 0x0100;
        const UInt32 SWP_NOOWNERZORDER = 0x0200;
        const UInt32 SWP_NOSENDCHANGING = 0x0400;

        [System.Runtime.InteropServices.DllImport("user32.dll")]
        static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        static bool save5 = true;
        static void Main(string[] args)
        {
            var username = Environment.UserName;
            var date = Environment.TickCount;
            Console.Title = "Password.Creator by Zekoyka | CONSOLE EDITION";

            IntPtr handle = GetConsoleWindow();
            IntPtr sysMenu = GetSystemMenu(handle, false);

            if (handle != IntPtr.Zero)
            {
                DeleteMenu(sysMenu, SC_MINIMIZE, MF_BYCOMMAND);
                DeleteMenu(sysMenu, SC_MAXIMIZE, MF_BYCOMMAND);
                DeleteMenu(sysMenu, SC_SIZE, MF_BYCOMMAND);
            }

            IntPtr ConsoleHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
            const UInt32 WINDOW_FLAGS = SWP_SHOWWINDOW;

            SetWindowPos(ConsoleHandle, HWND_NOTOPMOST, 0, 0, 500, 350, WINDOW_FLAGS);

            List<string> list = new List<string>();

            StreamWriter sw = new StreamWriter("C:\\Users\\" + username +"\\Downloads\\passwords.txt");

            while (true)
            {
                Console.Write("\n Кол-во генерируемых паролей: ");
                int colvo = Convert.ToInt32(Console.ReadLine());

                Console.Write("\n Длина пароля: ");
                int length = Convert.ToInt32(Console.ReadLine());

                Console.Write("\n Пароль с буквами верхнего регистра (ABC)? [Y/N]: ");
                string opinion0 = Console.ReadLine();
                if (opinion0 == "Y" || opinion0 == "y")
                {
                    list.Add(GetRangeString('A', 26)); // ABCDEFGHIJKLMNOPQRSTUVWXYZ
                }

                Console.Write("\n Пароль с буквами нижнего регистра (abc)? [Y/N]: ");
                string opinion1 = Console.ReadLine();
                if (opinion1 == "Y" || opinion1 == "y")
                {
                    list.Add(GetRangeString('a', 26)); // abcdefghijklmnopqrstuvwxyz
                }

                Console.Write("\n Пароль с цифрами (123)? [Y/N]: ");
                string opinion2 = Console.ReadLine();
                if (opinion2 == "Y" || opinion2 == "y")
                {
                    list.Add(GetRangeString('0', 10)); // 0123456789
                }

                Console.Write("\n Пароль с символами (123)? [Y/N]: ");
                string opinion3 = Console.ReadLine();
                if (opinion3 == "Y" || opinion3 == "y")
                {
                    list.Add(@"`~!@#$%^&*(@)-_=+[];:{}\|/.,<>№"); // `~!@#$%^&*(@)-_=+[];:{}\|/.,<>№
                }

                string dictionary = string.Concat(string.Concat(list).Distinct());

                for (int a = 0; a < colvo; a++)
                {
                    string password = GeneratePassword(dictionary, length);
                    if (save5 == true)
                    {
                        sw.WriteLine(password);
                        sw.Close();
                    }
                    Console.WriteLine(password);
                }
                Console.ReadKey();
            }
        }

        private static string GeneratePassword(string dictionary, int length)
        {
            Random rnd = new Random();
            return string.Concat(Enumerable.Repeat(0, length).Select(_ => dictionary[rnd.Next(dictionary.Length)]));
        }

        private static string GetRangeString(char first, int length)
        {
            return string.Concat(Enumerable.Range(first, length).Select(c => (char)c));
        }
    }
}

3
  • 1
    зачем же вы его закрываете, раз дальше, возможно, будете ещё писать? Вынесите строчку sw.Close(); из цикла 21 дек 2021 в 21:10
  • и вместо if (save5 == true) предпочтительней писать if (save5) 21 дек 2021 в 21:11
  • А, ого я конечно пропустил, хпхпхп, немного посмеялся даже =). Но я так думал что - записываю значение - закрываю, возращаюсь к циклу, открываю - записываю - и так по кругу. Большое спасибо >.
    – Zekoyka
    21 дек 2021 в 21:13

1 ответ 1

3

зачем же вы его закрываете, раз дальше, возможно, будете ещё писать? Вынесите строчку sw.Close(); из цикла – KuzCode

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.