Форум программистов, компьютерный форум, киберфорум
C# Windows Forms
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.60/5: Рейтинг темы: голосов - 5, средняя оценка - 4.60
145 / 145 / 35
Регистрация: 04.06.2011
Сообщений: 578

Консольный проект переписать в Win forms

05.09.2012, 12:06. Показов 1102. Ответов 2
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Код не мой нашёл на этом форуме))
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
 
namespace VkDownloadPage
{
    class Program
    {
        static private CookieContainer cookie;
        static public string stringFaveUrl = "http://vk.com/search"; //Страница, которую нужно загрузить
        static public string stringUserAgent = "Safari/5.05 (Windows; U; Windows NT 6.0; ru; rv:1.9.2.13) Net/02022012 Safari/5.05.112";
        static string login = ""; // Не забудьте указать логин и пароль!!!
        static string password = "";
 
        static void Main(string[] args)
        {
            ReadCookiesFromFile();
            string content = "";
            Reload(ref content);
            Console.WriteLine("Download complete!");
 
            StreamWriter sw = new StreamWriter("content.htm", false, Encoding.GetEncoding(1251));
            sw.Write(content);
            sw.Close();
            Console.ReadKey();
        }
 
        static private void ReadCookiesFromFile()
        {
            try
            {
                IFormatter formatter = new BinaryFormatter();
                Stream stream = new FileStream("cookies.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
                try
                {
                    cookie = (CookieContainer)formatter.Deserialize(stream);
                }
                catch { }
                stream.Close();
            }
            catch
            {
                cookie = new CookieContainer();
            }
        }
 
        static private void Reload(ref string content)
        {
            #region Load page
            int position;
            content = "";
            bool error = true;
            while (error)
            {
                try
                {
                    Console.WriteLine("Loading...");
                    error = false;
                    WebResponse response;
                    Stream receiveStream;
                    StreamReader readStream;
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(stringFaveUrl);
                    request.UserAgent = stringUserAgent;
                    request.Timeout = 15000;
                    request.CookieContainer = cookie;
                    response = request.GetResponse();
                    #region if (request.Address.AbsolutePath == "/login.php")
                    if (request.Address.AbsolutePath == "/login.php") // if need autorization
                    {
                        Console.WriteLine("Autorization...");
                        cookie = request.CookieContainer;
                        receiveStream = response.GetResponseStream();
                        readStream = new StreamReader(receiveStream, Encoding.Default);
                        content = readStream.ReadToEnd();
                        position = content.IndexOf("name=\"to\"");
                        if (position == -1)
                        {
                            Console.WriteLine("Error autorization (not find \"ip_h\")");
                            return;
                        }
                        else
                        {
                            position = content.IndexOf("value=\"", position);
                            position += 7;
                            int currentPosition;
                            for (currentPosition = position; content[currentPosition] != '"'; currentPosition++) ;
                            string to = content.Substring(position, currentPosition - position);
 
                            position = content.IndexOf("name=\"ip_h\"", currentPosition);
                            string ip_h;
                            if (position == -1)
                            {
                                position = content.IndexOf("name=\"ip_h\"");
                                if (position == -1)
                                {
                                    Console.WriteLine("Error autorization (not find \"ip_h\")");
                                    return;
                                }
                            }
                            else
                            {
                                position += 19;
                                for (currentPosition = position; content[currentPosition] != '"'; currentPosition++) ;
                                ip_h = content.Substring(position, currentPosition - position);
 
                                request = (HttpWebRequest)WebRequest.Create("https://login.vk.com/");
                                request.Referer = "http://vk.com/login.php";
                                request.Method = "POST";
                                request.Timeout = 15000;
                                request.UserAgent = stringUserAgent;
                                request.CookieContainer = cookie;
                                request.ContentType = "application/x-www-form-urlencoded";
                                string post = "act=login&success_url=&fail_url=&try_to_login=1&to=" + to
                                                + "&al_test=3&from_host=vk.com&from_protocol=http&ip_h=" + ip_h
                                                + "&email=" + login + "&pass=" + password;
                                byte[] postByte = new UTF8Encoding().GetBytes(post);
                                request.ContentLength = postByte.Length;
                                receiveStream = request.GetRequestStream();
                                receiveStream.Write(postByte, 0, postByte.Length);
                                receiveStream.Close();
                                response = request.GetResponse();
                                cookie = request.CookieContainer;
                                if (request.Address.PathAndQuery.StartsWith("/login.php?m=1&email="))
                                {
                                    Console.WriteLine("Invalid login or password");
                                    error = true;
                                    continue;
                                }
                                else if (request.Address.PathAndQuery.StartsWith("/login.php"))
                                {
                                    Console.WriteLine("Error autorization.");
                                    return;
                                }
                            }
                        }
                    }
                    #endregion
                    Console.WriteLine("LoadingInformation...");
 
                    receiveStream = response.GetResponseStream();
                    readStream = new StreamReader(receiveStream, Encoding.Default);
 
                    try
                    {
                        content = readStream.ReadToEnd();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Error!" + e.Message);
                        return;
                    }
 
                    IFormatter formatter = new BinaryFormatter();
                    Stream stream = new FileStream("cookies.bin", FileMode.Create, FileAccess.Write, FileShare.None);
                    cookie = request.CookieContainer;
                    formatter.Serialize(stream, cookie);
                    stream.Close();
 
                    response.Close();
                    readStream.Close();
                    readStream.Dispose();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error getting page!" + e.Message);
                    return;
                }
            }
            #endregion
            if (content.Length > 5)
            {
                return;
            }
            else
            {
                Console.WriteLine("Error getting page!");
                return;
            }
        }
 
    }
}
Но после того как я переписал под win forms программа перестала проходить аутентификацию и не пойму почему.
Вот мой код
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
 
namespace new_auth_vk
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            
        }
 
        private CookieContainer cookie;
        public string stringUrl = "http://vk.com/search";
        public string stringUserAgent = "Safari/5.05 (Windows; U; Windows NT 6.0; ru; rv:1.9.2.13) Net/02022012 Safari/5.05.112";
        string login;
        string pass;
        string content;
 
        private void ReadCookiesFile()
        {
            try
            {
                IFormatter formatter = new BinaryFormatter();
                Stream stream = new FileStream("cookies.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
                try
                {
                    cookie = (CookieContainer)formatter.Deserialize(stream);
                }
 
                catch{}
                stream.Close();
            }
 
            catch
            {
                cookie = new CookieContainer();
            }
        }
 
        private void Reload()
        {
            int position;
            content = "";
            bool error = true;
 
            while (error)
            {
                try
                {
                    error = false;
                    WebResponse response;
                    Stream receiveStream;
                    StreamReader readStream;
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(stringUrl);
                    request.UserAgent = stringUserAgent;
                    request.Timeout = 15000;
                    request.CookieContainer = cookie;
                    response = request.GetResponse();
 
                    if (request.Address.AbsolutePath == "/login.php")
                    {
                        cookie = request.CookieContainer;
                        receiveStream = response.GetResponseStream();
                        readStream = new StreamReader(receiveStream, Encoding.Default);
                        content = readStream.ReadToEnd();
                        position = content.IndexOf("name=\"to\"");
 
                        if (position == -1)
                        {
                            MessageBox.Show("Ошибка авторизации! (не найдён \"ip_\")");
                            return;
                        }
 
                        else
                        {
                            position = content.IndexOf("value=\"", position);
                            position += 7;
                            int currentPosition;
 
                            for (currentPosition = position; content[currentPosition] != '"'; currentPosition++) ;
                            string to = content.Substring(position, currentPosition - position);
 
                            position = content.IndexOf("name=\"ip_h\"", currentPosition);
                            string ip_h;
                            if (position == 1)
                            {
                                position = content.IndexOf("name=\"ip_h\"");
 
                                if (position == -1)
                                {
                                    MessageBox.Show("Ошибка авторизации! (не найдён \"ip_\")");
                                    return;
                                }
                            }
 
                            else
                            {
                                position += 19;
 
                                for (currentPosition = position; content[currentPosition] != '"'; currentPosition++) ;
                                ip_h = content.Substring(position, currentPosition - position);
 
                                request = (HttpWebRequest)WebRequest.Create("https://login.vk.com/");
                                request.Referer = "http://vk.com/login.php";
                                request.Method = "POST";
                                request.Timeout = 15000;
                                request.UserAgent = stringUserAgent;
                                request.CookieContainer = cookie;
                                request.ContentType = "application/x-www-form-urlencoded";
 
                                string post = "act=login&success_url=&fail_url=&try_to_login=1&to=" + to
                                                + "&al_test=3&from_host=vk.com&from_protocol=http&ip_h=" + ip_h
                                                + "&email=" + textBox1.Text + "&pass=" + textBox2.Text;
 
                                byte[] postByte = new UTF8Encoding().GetBytes(post);
                                request.ContentLength = postByte.Length;
                                receiveStream = request.GetRequestStream();
                                receiveStream.Write(postByte, 0, postByte.Length);
                                receiveStream.Close();
                                response = request.GetResponse();
                                cookie = request.CookieContainer;
 
                                if (request.Address.PathAndQuery.StartsWith("/login.php?m=1&email="))
                                {
                                    MessageBox.Show("Неверный пароль или логин!");
                                    error = true;
                                    continue;
                                }
 
                                else if (request.Address.PathAndQuery.StartsWith("/login.php?m=1&email="))
                                {
                                    MessageBox.Show("Ошибка авторизации!");
                                    return;
                                }
                            }
                        }
                    }
 
                    MessageBox.Show("Загрузка...");
 
                    receiveStream = response.GetResponseStream();
                    readStream = new StreamReader(receiveStream, Encoding.Default);
 
                    try
                    {
                        content = readStream.ReadToEnd();
                    }
 
                    catch (Exception e)
                    {
                        MessageBox.Show("Ошибка!" + e.Message);
                        return;
                    }
 
                    IFormatter formatter = new BinaryFormatter();
                    Stream stream = new FileStream("cookies.bin", FileMode.Create, FileAccess.Write, FileShare.None);
                    cookie = request.CookieContainer;
                    formatter.Serialize(stream, cookie);
                    stream.Close();
 
                    response.Close();
                    readStream.Close();
                    readStream.Dispose();
                }
                catch (Exception e)
                {
                    MessageBox.Show("Ошибка получения страницы!" + e.Message);
                    return;
                }
            }
 
            if (content.Length > 5)
            {
                return;
            }
 
            else
            {
                MessageBox.Show("Ошибка получения страницы!");
                return;
            }
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            ReadCookiesFile();
            Reload();
 
            MessageBox.Show("Скачивание завершено!");
 
            StreamWriter sw = new StreamWriter("content.html", false, Encoding.GetEncoding(1251));
            sw.Write(content);
            sw.Close();
        }
    }
}
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
05.09.2012, 12:06
Ответы с готовыми решениями:

Как в консольный проект подключить System.Windiws.Forms
У меня Microsoft Visual C# 2008 Express Edition, создал пустой проект и теперь немогу подключить пространство имен System.Windiws.Forms ,...

Переписать программу на консольный режим
Переписать программу на консольный режим: using System; using System.Collections.Generic; using System.ComponentModel; using...

libcurl in win forms
При создании пустого проекта и подключении libcurl все работает на ура,при использовании libcurl в WinForms в режиме Debug так же все...

2
556 / 510 / 25
Регистрация: 23.07.2009
Сообщений: 2,359
Записей в блоге: 1
05.09.2012, 12:24
Цитата Сообщение от Andrew_qb Посмотреть сообщение
Но после того как я переписал под win forms программа перестала проходить аутентификацию и не пойму почему.
оно ж тебе что-то возвращает, почитай, может на что наведет.
0
145 / 145 / 35
Регистрация: 04.06.2011
Сообщений: 578
06.09.2012, 10:49  [ТС]
Цитата Сообщение от novi4ok Посмотреть сообщение
оно ж тебе что-то возвращает, почитай, может на что наведет.
У меня только одно предположение в консольном проекте вызывалась переменная "conten" через ref а у меня это просто глобальная переменная и я вот без понятия что делать.

Добавлено через 22 часа 11 минут
UP! что ни кто не поможет?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
06.09.2012, 10:49
Помогаю со студенческими работами здесь

Потоки в Win Forms
Всем привет! Я создал поток. Во всяком случае так написано в MSDN :) Вот код: (Я перепробовал все варианты в 7 самы частых вопросах,...

Выезжающие окна на Win Forms
Еще раз всем привет! Интересует вопрос, можно ли как-то силами C# сделать "выезжаюзие" менюшки или "вклинивающиеся"...

Win Forms + JavaScript в теории
Здравствуйте! Возможно ли работа Windows forms с JavaScript? Я хотела бы больше научиться программированию на придуманной задаче...

Создание картотеки в Win Forms
Добрый вечер. Пишу вот с таким вопросом. Перевелся в другой универ а там нужно сдать С#. Но дело не в этом. Дали задание сделать...

фоновое Win Forms приложение с таймером
Необходимо написать приложение которое при запуске работало в фоновом режиме и раз в 5-10 минут (рандомно) выбивало бы окно на которое...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
3
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru