Форум программистов, компьютерный форум, киберфорум
C# для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.57/82: Рейтинг темы: голосов - 82, средняя оценка - 4.57
133 / 133 / 29
Регистрация: 17.09.2010
Сообщений: 288

Сохранение текста в файл.

17.09.2010, 18:48. Показов 17266. Ответов 7
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Добрый вечер! Хочу сохранять в txt файл, а он постоянно переписывается, подскажите, что я делаю не так?
Код
Code
1
2
3
4
StreamWriter writeSiteInfo = new StreamWriter("Data\\Logins.dat");
writeSiteInfo.WriteLine("[" + lstSite.Items[lstSite.SelectedIndex].ToString() + "]");
writeSiteInfo.WriteLine(txtLogin.Text);
writeSiteInfo.Close();
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
17.09.2010, 18:48
Ответы с готовыми решениями:

Сохранение текста из консоли в файл
Здравствуйте! Как сделать, чтобы в консоле вводить текст и он сохранялся в файл, и чтоб из этого файла можно было вывести то, что в...

Сохранение форматированного текста в двоичный файл
Здравствуйте. У меня есть объект, который я записываю в бинарный файл. Также есть форматированный текст в формате rtf. Можно ли как-то...

Чтение и сохранение текста в файл в кодировке по умолчанию
Здравствуйте. Извиняюсь если уже было, но впервые столкнулся с такой проблемой: Дан файл .txt в стандартной кодировке (не помню в...

7
49 / 49 / 3
Регистрация: 15.11.2009
Сообщений: 372
17.09.2010, 19:16
eji,
Не удивительно, что он у вас постоянно перезаписывается
Сделайте так:
C#
1
2
3
4
5
6
7
8
using (FileStream fs = new FileStream("Data\\Logins.dat", FileMode.Append))
            {
                using (StreamWriter sw = new StreamWriter(fs))
                {
                    sw.WriteLine(("[" + lstSite.Items[lstSite.SelectedIndex].ToString() + "]"));
                    sw.WriteLine(txtLogin.Text);
                }
            }
Добавлено через 46 секунд
FileMode.Append позволяет дописывать в файл
1
Почетный модератор
Эксперт .NET
 Аватар для NickoTin
8729 / 3681 / 404
Регистрация: 14.06.2010
Сообщений: 4,513
Записей в блоге: 9
17.09.2010, 19:39
C#
1
2
3
4
5
6
using (StreamWriter sw = new StreamWriter("X:\\some.txt", true))
{
    sw.WriteLine("[" + lstSite.Items[lstSite.SelectedIndex].ToString() + "]");
    sw.WriteLine(txtLogin.Text);
    sw.Close();
}
1
133 / 133 / 29
Регистрация: 17.09.2010
Сообщений: 288
17.09.2010, 19:48  [ТС]
Спасибо, с этим понятно. А вот если мне нужно хранить настройки в файле ini, можете пример маленький показать?
0
Почетный модератор
Эксперт .NET
 Аватар для NickoTin
8729 / 3681 / 404
Регистрация: 14.06.2010
Сообщений: 4,513
Записей в блоге: 9
17.09.2010, 19:53
А ini обязателен? Используйте Settings.
1
133 / 133 / 29
Регистрация: 17.09.2010
Сообщений: 288
17.09.2010, 20:10  [ТС]
SSTREGG, дело в том, что я пробовал, но не получается програмно добавить, к примеру "string 1".
0
Почетный модератор
Эксперт .NET
 Аватар для NickoTin
8729 / 3681 / 404
Регистрация: 14.06.2010
Сообщений: 4,513
Записей в блоге: 9
17.09.2010, 20:26
Вот класс для работы с ini (писАл очень давно)):
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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.IO;
...
public class INI
{
    #region Declarations
    private string iniPath = null;
    private const int INI_BUFFSIZE = 1024;
    #endregion
 
    #region API::Error
 
    [DllImport("kernel32.dll")]
    private static extern int GetLastError();
 
    #endregion
 
    #region API::Read
 
    [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileStringA")]
    private static extern int GetPrivateProfileString(
        string lpApplicationName,
        string lpKeyName,
        string lpDefault,
        StringBuilder lpReturnedString,
        int nSize,
        string lpFileName);
 
    #endregion
 
    #region API::Write
 
    [DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileSectionA")]
    private static extern int WritePrivateProfileSection(
        string lpAppName,
        string lpString,
        string lpFileName);
 
    [DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileStringA")]
    private static extern int WritePrivateProfileString(
        string lpApplicationName,
        string lpKeyName,
        string lpString,
        string lpFileName);
 
    #endregion
 
    #region Code
    // Set/Get File path
    public string Path
    {
        get { return iniPath; }
        set { iniPath = value; }
    }
 
    #region Constructors
    public INI()
    {
        // TODO
    }
 
    public INI(string Path)
    {
        iniPath = Path;
    }
    #endregion
 
    // return != null [no error]
    public string GetValue(string Section, string KeyName, string Default)
    {
        int err = 0;
 
        if (iniPath == null)
            throw new NullReferenceException("File path not initialized(null)!");
        else if (!File.Exists(iniPath))
            throw new IOException("File '" + iniPath + "' not found!", 1);
        else if (Section == null)
            throw new NullReferenceException("Section not initialized(null)!");
        else if (KeyName == null)
            throw new NullReferenceException("KeyName not initialized(null)!");
 
        StringBuilder tmp = new  StringBuilder(INI_BUFFSIZE);
 
        err = GetPrivateProfileString(Section, KeyName, Default, tmp, INI_BUFFSIZE, iniPath);
 
        if (err == 0)
            return null;
        else
            return tmp.ToString();
    }
 
    // return != 0 [no error]
    public int GetValue(string Section, string KeyName, int Default)
    {
        int err = 0;
 
        if (iniPath == null)
            throw new NullReferenceException("File path not initialized(null)!");
        else if (!File.Exists(iniPath))
            throw new IOException("File '" + iniPath + "' not found!", 1);
        else if (Section == null)
            throw new NullReferenceException("Section not initialized(null)!");
        else if (KeyName == null)
            throw new NullReferenceException("KeyName not initialized(null)!");
 
        StringBuilder tmp = new StringBuilder(INI_BUFFSIZE);
 
        int temp = 0;
 
        err = GetPrivateProfileString(Section, KeyName, Default.ToString(), tmp, INI_BUFFSIZE, iniPath);
 
        if (err == 0)
            return -1;
        else
            return (int.TryParse(tmp.ToString(),out temp) ? temp : Default);
    }
 
    // params = no; return != 0 [no error]
    public int WriteSection(string Section, string KeyNames)
    {
        int err = 0;
 
        if (iniPath == null)
            throw new NullReferenceException("File path not initialized(null)!");
        else if (!File.Exists(iniPath))
            throw new IOException("File '" + iniPath + "' not found!", 1);
        else if (Section == null)
            throw new NullReferenceException("Section not initialized(null)!");
 
        if (!KeyNames.EndsWith('\0'.ToString())) KeyNames += '\0';
 
        err = WritePrivateProfileSection(Section, KeyNames, iniPath);
 
        if (err == 0)
            return GetLastError();
        else
            return err;
    }
 
    // params = int; return != 0 [no error]
    public int WriteSection(string Section, string KeyNames, params int[] args)
    {
        string param = null;
        string[] keyv = KeyNames.Split('\0');
 
        int keyc = KeyNames.Split('\0').Length - 1;
 
        if (Section == null)
            throw new NullReferenceException("Section not initialized(null)!");
        else if (keyc != args.Length - 1)
            throw new Exception("KeyNames length not equals params length!");
 
        for (int i = 0; i <= keyc; i++)
        {
            if (keyv[i] != null && keyv[i].Trim() != "")
                param += keyv[i] + '=' + args[i] + '\r';
        }
 
        int err = 0;
 
        if (iniPath == null)
            throw new NullReferenceException("File path not initialized(null)!");
        else if (!File.Exists(iniPath))
            throw new IOException("File '" + iniPath + "' not found!", 1);
 
        if (!param.EndsWith('\0'.ToString())) param += '\0';
 
        err = WritePrivateProfileSection(Section, param, iniPath);
        if (err == 0)
            return GetLastError();
        else
            return err;
    }
 
    // params = string; return != 0 [no error]
    public int WriteSection(string Section, string KeyNames, params string[] args)
    {
        string param = null;
        string[] keyv = KeyNames.Split('\0');
 
        int keyc = KeyNames.Split('\0').Length - 1;
 
        if (Section == null)
            throw new NullReferenceException("Section not initialized(null)!");
        else if (keyc != args.Length - 1)
            throw new Exception("KeyNames length not equals params length!");
 
        for (int i = 0; i <= keyc; i++)
        {
            if (keyv[i] != null && keyv[i].Trim() != "")
                param += keyv[i] + '=' + args[i] + '\r';
        }
 
        int err = 0;
 
        if (iniPath == null)
            throw new NullReferenceException("File path not initialized(null)!");
        else if (!File.Exists(iniPath))
            throw new IOException("File '" + iniPath + "' not found!", 1);
 
        if (!param.EndsWith('\0'.ToString())) param += '\0';
 
        err = WritePrivateProfileSection(Section, param, iniPath);
 
        if (err == 0)
            return GetLastError();
        else
            return err;
    }
 
    // Value = string; return != 0 [no error]
    public int WriteValue(string Section, string KeyName, string Value)
    {
        int err = 0;
 
        if (iniPath == null)
            throw new NullReferenceException("File path not initialized(null)!");
        else if (!File.Exists(iniPath))
            throw new IOException("File '" + iniPath + "' not found!", 1);
        else if (Section == null)
            throw new NullReferenceException("Section not initialized(null)!");
        else if (KeyName == null)
            throw new NullReferenceException("KeyName not initialized(null)!");
        else if (Value == null)
            throw new NullReferenceException("Value not initialized(null)!");
 
        if (!KeyName.EndsWith('\0'.ToString())) KeyName += '\0';
 
        err = WritePrivateProfileString(Section, KeyName, Value, iniPath);
 
        if (err == 0)
            return GetLastError();
        else
            return err;
    }
 
    // Value = int; return != 0 [no error]
    public int WriteValue(string Section, string KeyName, int Value)
    {
        int err = 0;
 
        if (iniPath == null)
            throw new NullReferenceException("File path not initialized(null)!");
        else if (!File.Exists(iniPath))
            throw new IOException("File '" + iniPath + "' not found!", 1);
        else if (Section == null)
            throw new NullReferenceException("Section not initialized(null)!");
        else if (KeyName == null)
            throw new NullReferenceException("KeyName not initialized(null)!");
 
        if (!KeyName.EndsWith('\0'.ToString())) KeyName += '\0';
 
        err = WritePrivateProfileString(Section, KeyName, Value.ToString(), iniPath);
 
        if (err == 0)
            return GetLastError();
        else
            return err;
    }
 
    // return != 0 [no error]
    public int DeleteSection(string Section)
    {
        int err = 0;
 
        if (iniPath == null)
            throw new NullReferenceException("File path not initialized(null)!");
        else if (!File.Exists(iniPath))
            throw new IOException("File '" + iniPath + "' not found!", 1);
        else if (Section == null)
            throw new NullReferenceException("Section not initialized(null)!");
 
        err = WritePrivateProfileString(Section, null, null, iniPath);
 
        if (err == 0)
            return GetLastError();
        else
            return err;
    }
 
    // return != 0 [no error]
    public int DeleteValue(string Section, string KeyName)
    {
        int err = 0;
 
        if (iniPath == null)
            throw new NullReferenceException("File path not initialized(null)!");
        else if (!File.Exists(iniPath))
            throw new IOException("File '" + iniPath + "' not found!", 1);
        else if (Section == null)
            throw new NullReferenceException("Section not initialized(null)!");
        else if (KeyName == null)
            throw new NullReferenceException("KeyName not initialized(null)!");
 
        err = WritePrivateProfileString(Section, KeyName, null, iniPath);
 
        if (err == 0)
            return GetLastError();
        else
            return err;
    }
 
    public override string ToString()
    {
        return "System.INI=>" + iniPath;
    }
 
    #endregion
}
 
 
// Использование:
INI ini = new INI(/* путь */);
Но наверняка есть методы и с помощью Settings, если кто знает думаю ответит...
1
133 / 133 / 29
Регистрация: 17.09.2010
Сообщений: 288
18.09.2010, 16:37  [ТС]
SSTREGG, Спсибо за класс, буду разбираться! Хорошо бы strings освоить, может кто знает как программно создавать новые строки?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
18.09.2010, 16:37
Помогаю со студенческими работами здесь

Сохранение текста из RichTextBox в файл *.TXT с переносом строки
Как сделать вывод текста из RichTextBox в файл *.TXT так, чтобы переход на новую строку сохранился как в тексте. Пока у меня всё в одну...

Парсинг странички, выбор нужного текста и сохранение в файл csv
программа парсинга. Парсит странички,выберая нужный текст и сохраняет в файл csv. Сделал: 1 перебирает все странички с нужной инфой...

Сохранение текста в файл
Ребята, давно хотел спросить - какой самый (быстрый/компактный/удобный) способ сохранение текста в файл для вас? одной строки ( к примеру...

Сохранение текста в файл
Всем привет. У меня вопрос возник, я сохраняю текстовую информацию с Memo1-&gt;Lines-&gt;SaveToFile(&quot;Претенденты.doc&quot;); Когда я...

Сохранение текста в файл из 70 TextBox
Вопрос такой. На форме около 70 текстбоксов. При нажатии кнопки &quot;Сохранить&quot; нужно, чтобы все результаты сохранились в файл.


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

Или воспользуйтесь поиском по форуму:
8
Ответ Создать тему
Новые блоги и статьи
модель ЗдравоСохранения 8. Подготовка к разному выполнению заданий
anaschu 08.04.2026
https:/ / github. com/ shumilovas/ med2. git main ветка * содержимое блока дэлэй из старой модели теперь внутри зайца новой модели 8ATzM_2aurI
Блокировка документа от изменений, если он открыт у другого пользователя
Maks 08.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа, разработанного в конфигурации КА2. Задача: запретить редактирование документа, если он открыт у другого пользователя. / / . . .
Система безопасности+живучести для сервера-слоя интернета (сети). Двойная привязка.
Hrethgir 08.04.2026
Далее были размышления о системе безопасности. Сообщения с наклонным текстом - мои. А как нам будет можно проверить, что ссылка наша, а не подделана хулиганами, которая выбросит на другую ветку и. . .
Модель ЗдрввоСохранения 7: больше работников, больше ресурсов.
anaschu 08.04.2026
работников и заданий может быть сколько угодно, но настроено всё так, что используется пока что только 20% kYBz3eJf3jQ
Дальние перспективы сервера - слоя сети с космологическим дизайном интефейса карты и логики.
Hrethgir 07.04.2026
Дальнейшее ближайшее планирование вывело к размышлениям над дальними перспективами. И вот тут может быть даже будут нужны оценки специалистов, так как в дальних перспективах всё может очень сильно. . .
Горе от ума
kumehtar 07.04.2026
Эта мне ментальная установка, что вот прямо сейчас, мол, мне для полного счастья не хватает (нужное вписать), и когда я этого достигну - тогда и полный кайф. Одна из самых сильных ловушек на пути. . . .
Использование значений реквизитов справочника в документе, с определенными условиями и правами
Maks 07.04.2026
1. Контроль срока действия договора Алгоритм из решения ниже реализован на примере нетипового документа "ЗаявкаНаРаботу", разработанного в конфигурации КА2. Задача: уведомлять пользователя, если. . .
Доступность команды формы по условию
Maks 07.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: сделать доступной кнопку (команда формы "ЗавершитьСписание") при. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru