Вывод в файл c windows form

There are a lot of different ways to read and write files (text files, not binary) in C#. I just need something that is easy and uses the least amount of code, because I am going to be working with

These are the best and most commonly used methods for writing to and reading from files:

using System.IO;

File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it. 
File.ReadAllText(sFilePathAndName);

The old way, which I was taught in college was to use stream reader/stream writer, but the File I/O methods are less clunky and require fewer lines of code. You can type in «File.» in your IDE (make sure you include the System.IO import statement) and see all the methods available. Below are example methods for reading/writing strings to/from text files (.txt.) using a Windows Forms App.

Append text to an existing file:

private void AppendTextToExistingFile_Click(object sender, EventArgs e)
{
    string sTextToAppend = txtMainUserInput.Text;
    //first, check to make sure that the user entered something in the text box.
    if (sTextToAppend == "" || sTextToAppend == null)
    {MessageBox.Show("You did not enter any text. Please try again");}
    else
    {
        string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a pathfilename.txt as string.
        if (sFilePathAndName == "" || sFilePathAndName == null)
        {
            //MessageBox.Show("You cancalled"); //DO NOTHING
        }
        else 
        {
            sTextToAppend = ("rn" + sTextToAppend);//create a new line for the new text
            File.AppendAllText(sFilePathAndName, sTextToAppend);
            string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\') + 1);
            MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
        }//end nested if/else
    }//end if/else

}//end method AppendTextToExistingFile_Click

Get file name from the user via file explorer/open file dialog (you will need this to select existing files).

private string getFileNameFromUser()//returns file pathname
{
    string sFileNameAndPath = "";
    OpenFileDialog fd = new OpenFileDialog();
    fd.Title = "Select file";
    fd.Filter = "TXT files|*.txt";
    fd.InitialDirectory = Environment.CurrentDirectory;
    if (fd.ShowDialog() == DialogResult.OK)
    {
        sFileNameAndPath = (fd.FileName.ToString());
    }
    return sFileNameAndPath;
}//end method getFileNameFromUser

Get text from an existing file:

private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
    string sFileNameAndPath = getFileNameFromUser();
    txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}

These are the best and most commonly used methods for writing to and reading from files:

using System.IO;

File.AppendAllText(sFilePathAndName, sTextToWrite);//add text to existing file
File.WriteAllText(sFilePathAndName, sTextToWrite);//will overwrite the text in the existing file. If the file doesn't exist, it will create it. 
File.ReadAllText(sFilePathAndName);

The old way, which I was taught in college was to use stream reader/stream writer, but the File I/O methods are less clunky and require fewer lines of code. You can type in «File.» in your IDE (make sure you include the System.IO import statement) and see all the methods available. Below are example methods for reading/writing strings to/from text files (.txt.) using a Windows Forms App.

Append text to an existing file:

private void AppendTextToExistingFile_Click(object sender, EventArgs e)
{
    string sTextToAppend = txtMainUserInput.Text;
    //first, check to make sure that the user entered something in the text box.
    if (sTextToAppend == "" || sTextToAppend == null)
    {MessageBox.Show("You did not enter any text. Please try again");}
    else
    {
        string sFilePathAndName = getFileNameFromUser();// opens the file dailog; user selects a file (.txt filter) and the method returns a pathfilename.txt as string.
        if (sFilePathAndName == "" || sFilePathAndName == null)
        {
            //MessageBox.Show("You cancalled"); //DO NOTHING
        }
        else 
        {
            sTextToAppend = ("rn" + sTextToAppend);//create a new line for the new text
            File.AppendAllText(sFilePathAndName, sTextToAppend);
            string sFileNameOnly = sFilePathAndName.Substring(sFilePathAndName.LastIndexOf('\') + 1);
            MessageBox.Show("Your new text has been appended to " + sFileNameOnly);
        }//end nested if/else
    }//end if/else

}//end method AppendTextToExistingFile_Click

Get file name from the user via file explorer/open file dialog (you will need this to select existing files).

private string getFileNameFromUser()//returns file pathname
{
    string sFileNameAndPath = "";
    OpenFileDialog fd = new OpenFileDialog();
    fd.Title = "Select file";
    fd.Filter = "TXT files|*.txt";
    fd.InitialDirectory = Environment.CurrentDirectory;
    if (fd.ShowDialog() == DialogResult.OK)
    {
        sFileNameAndPath = (fd.FileName.ToString());
    }
    return sFileNameAndPath;
}//end method getFileNameFromUser

Get text from an existing file:

private void btnGetTextFromExistingFile_Click(object sender, EventArgs e)
{
    string sFileNameAndPath = getFileNameFromUser();
    txtMainUserInput.Text = File.ReadAllText(sFileNameAndPath); //display the text
}

Дата изменения: 8 декабря 2022

Лабораторные работы си шарп. Работа с файлами

Приложения для Windows forms

Лабораторная работа 15

Выполнить: Разработайте приложение, которое сохраняет в файл информацию из списка (ListBox) и загружает из файла информацию обратно в список.

Пример выполнения:
Работа с файлами в C#

[Название проекта: Lesson_15Lab1, название файла L15Lab1.cs]

✍ Выполнение:

  1. Поместите на форму элементы: список ListBox (lst), ListBox (lstFromfile) текстовое поле TextBox (txt), кнопки: btnAdd («Добавить элемент в список»), btnSave («Сохранить в файле»), btnOpen («Загрузить из файла»). Расположите правильно элементы (рисунок).
  2. Добавьте пространство имен для работы с файлами:
  3. При нажатии на btnAdd («Добавить элемент в список») в список lst должна добавиться строка, записанная в текстовое окно txt, а само окно при этом должно очиститься. Добавьте код для события click кнопки btnAdd:
  4. 1
    2
    3
    4
    5
    
    private void btnAdd_Click(object sender, EventArgs e)
            {
                lst.Items.Add(txt.Text);
                txt.Clear();
            }
  5. По щелчку на кнопке btnSave вся информация со списка должна добавляться во введенный пользователем в текстовое окно текстовый файл. Для этого добавьте процедуру для события Click кнопки:
  6. 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    
    private void btnSave_Click(object sender, EventArgs e)
            {
                string fileName = txtFileName.Text; // путь к файлу
                if (File.Exists(fileName)) 
                {
                    File.Delete(fileName); // если файл существует - удаляем его
                }
                using (FileStream fs = File.Create(fileName, 1024)) // класс для работы с файлами
    // класс для работы с данными файла в двоичной виде
                using(BinaryWriter bw = new BinaryWriter(fs)) 
                {
                    for (var i = 0; i < lst.Items.Count; i++) // пока не конец списка
                    {
                        bw.Write(lst.Items[i].ToString()); // записываем в файл каждый пункт
     
                    }
                    bw.Close();
                    fs.Close();
                }
              }
  7. Событие Click кнопки btnOpen («Загрузить из файла») запрограммируйте таким образом, чтобы в список помещались все строки из файла:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private void btnOpen_Click(object sender, EventArgs e)
        {
            string fileName = txtFileName.Text;
            lstFromfile.Items.Clear();
            using (FileStream fs = new FileStream(fileName, FileMode.Open))
            using (BinaryReader br = new BinaryReader(fs))
            {
             // метод PeekChar() возвращает следующий прочитанный символ
             // если символов нет - возвращается -1
                while (br.PeekChar() != -1) 
                {
                    // добавляем в список очередную прочитанную строку
                    lstFromfile.Items.Add(br.ReadString()); 
                }
                br.Close();
                fs.Close();
            }
        }
  1. Запустите приложение, внесите в список lst несколько строк и попытайтесь сохранить их в файл (желательно с расширением .txt: например, proba.txt). Если не написан путь к файлу, то файл сохранится в папке /bin/Debug Вашего проекта.

The Save File Dialog control (System.Windows.Forms.SaveFileDialog) allows you to save or write data to a specified file. The dialog allows you to browse your file system and pick a directory, then type a filename you want to be the name of the file that will contain the data to be written. You can type the name of the file that exist in the current directory and the dialog can prompt you if you want to overwrite it. You can also type the whole path of a file or directory in the File Name text box located at the bottom of the dialog.

savefiledialog

savefiledialog

The following table shows some useful properties of the SaveFileDialog control.

Property Description
AddExtention Specifies whether to automatically add an extension when the user does not specify a file extension.
CheckFileExists Specifies whether to initiate a warning if the user types a file that does not exist.
CheckPathExists Specifies whether to initiate a warning if the user types a path that does not exist.
DefaultExt The default extensions to add when the user does not indicate a file extension.
FileName The file selected by the user. This can also be the default selected the file when the dialog shows up.
Filter Allows you to add a filter which are a special string indicating which types or files are only allowed to be opened by the user.
FilterIndex If multiple filters are present, this indicates which filter shows as the default starting with index 1.
InitialDirectory The initial directory that the OpenFileDialog will show.
OverwritePrompt Specifies whether the dialog will prompt you to overwrite a file when an existing file is already found.
RestoreDirectory Specifies whether to restore to default directory when the dialog closes.
Title The title of the dialog.

The AddExtention property automatically adds an extension when the user does not indicate the file extension of the file name. The extension to add is specified by the DefaultExt property. The CheckFileExists and CheckPathExists methods are recommended to be set to true so the dialog will issue a warning message if it cannot find the specified file or directory. The InitialDirectory property specifies the initial directory that the dialog will show when you open it up. The Title property is the title of the dialog located at the title bar. The FileName property is the Filename specified by the user.

Specifying File Types


We can specify the file types that the file will have. We use the Filter property which accepts a string containing a special pattern. For example, we can set the dialog to only allow our file to be saved as a text file with .txt file extensions. The Filter property requires a special pattern.

Description1|Extension1|Description2|Extention2|...DescriptionN|ExtentionN

We first start with a description telling about the type of file. We then follow it with a vertical bar (|) followed by the extension. For example, the following pattern allows you to save files as text files.

Text Files|.txt

The description here is Text Files and the extension are .txt. You can specify multiple extensions. For example, the following pattern allows you to save a file as a .txt, or .png.

Text Files|*.txt|Image|*.png

You can select the type that the file will be saved as using the combo box below the File Name text box.

savefiledialog

savefiledialog

SaveFileDialog Control Example


We will now create an example application that uses the basic capabilities of the SaveFileDialog control. The application will allow a user to type into a multiline text box and then save the text into a text file using a specified file name and path. Please note that we need to import the System.IO namespace in our code.

using System.IO;

Create a form similar to the one below. Use a multiline text box by setting the Multiline property to true. Drag a SaveFileDialog control from the Dialogs category of the Toolbox to the form.

savefiledialog

savefiledialog

Double-click the button to create an event handler for its Click event. Again, import the System.IO namespace first at the top of the code. Use the following code for the event handler.

private void button1_Click(object sender, EventArgs e)
{
    //Specify the extensions allowed
    saveFileDialog1.Filter = "Text File|.txt";
    //Empty the FileName text box of the dialog
    saveFileDialog1.FileName = String.Empty;
    //Set default extension as .txt
    saveFileDialog1.DefaultExt = ".txt";

    //Open the dialog and determine which button was pressed
    DialogResult result = saveFileDialog1.ShowDialog();

   
    if (result == DialogResult.OK)
    {
        //Create a file stream using the file name
        FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
        
       
        StreamWriter writer = new StreamWriter(fs);
        //Write the contents of the text box to the stream
        writer.Write(textBox1.Text);
        //Close the writer and the stream
        writer.Close();
    }
}

The first line specifies that we can only save our file as a text file with .txt extension. The second one assigns an empty string to the FileName so the File Name text box of the dialog will be initially empty (you can indicate a default filename though). We set the default extension to be .txt so if the user only types the name and forgot or do not include the extensions, the dialog will automatically add the extension name in case no file type is selected. We then open the SaveFileDialog using its ShowMethod property which returns a DialogResult value. The user can now browse the directory where he/she wants to save the file. When the user presses the Save button, then the method ShowDialog will return DialogResult.OK. We tested this using an if statement. We created a FileStreamobject and set the file name and file mode. We then create a StreamWriter object and pass the FileStream object. We use the Writemethod of the writer to write the contents of the text box to the stream and save it to the file. Finally, we close the writer which also closes the file stream.

Execute the application and type anything inside the text box. Click the button and choose a directory. Then type a file name and hit Save. If a similar file exists, you may be prompted if the program should overwrite the file. Setting OverwritePrompt to false will automatically overwrite the file without prompting.

Последнее обновление: 31.10.2015

Окна открытия и сохранения файла представлены классами OpenFileDialog и SaveFileDialog.
Они имеют во многом схожую функциональность, поэтому рассмотрим их вместе.

OpenFileDialog и SaveFileDialog имеют ряд общих свойств, среди которых можно выделить следующие:

  • DefaultExt: устанавливает расширение файла, которое добавляется по умолчанию, если пользователь ввел имя файла без расширения

  • AddExtension: при значении true добавляет к имени файла расширение при его отсуствии. Расширение берется из
    свойства DefaultExt или Filter

  • CheckFileExists: если имеет значение true, то проверяет существование файла с указанным именем

  • CheckPathExists: если имеет значение true, то проверяет существование пути к файлу с указанным именем

  • FileName: возвращает полное имя файла, выбранного в диалоговом окне

  • Filter: задает фильтр файлов, благодаря чему в диалоговом окне можно отфильтровать файлы по расширению. Фильтр задается в следующем формате
    Название_файлов|*.расширение. Например, Текстовые файлы(*.txt)|*.txt. Можно задать сразу несколько фильтров, для этого они разделяются
    вертикальной линией |. Например, Bitmap files (*.bmp)|*.bmp|Image files (*.jpg)|*.jpg

  • InitialDirectory: устанавливает каталог, который отображается при первом вызове окна

  • Title: заголовок диалогового окна

Отдельно у класса SaveFileDialog можно еще выделить пару свойств:

  • CreatePrompt: при значении true в случае, если указан не существующий файл, то будет отображаться сообщение о его создании

  • OverwritePrompt: при значении true в случае, если указан существующий файл, то будет отображаться сообщение о том, что файл будет перезаписан

Чтобы отобразить диалоговое окно, надо вызвать метод ShowDialog().

Рассмотрим оба диалоговых окна на примере. Добавим на форму текстовое поле textBox1 и две кнопки button1 и button2. Также перетащим с панели инструментов
компоненты OpenFileDialog и SaveFileDialog. После добавления они отобразятся внизу дизайнера формы. В итоге форма будет выглядеть примерно так:

OpenFileDialog и SaveFileDialog в Windows Forms

Теперь изменим код формы:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        button1.Click += button1_Click;
        button2.Click += button2_Click;
        openFileDialog1.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*";
        saveFileDialog1.Filter = "Text files(*.txt)|*.txt|All files(*.*)|*.*";
    }
    // сохранение файла
    void button2_Click(object sender, EventArgs e)
    {
        if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
            return;
        // получаем выбранный файл
        string filename = saveFileDialog1.FileName;
        // сохраняем текст в файл
        System.IO.File.WriteAllText(filename, textBox1.Text);
        MessageBox.Show("Файл сохранен");
    }
    // открытие файла
    void button1_Click(object sender, EventArgs e)
    {
        if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
            return;
        // получаем выбранный файл
        string filename = openFileDialog1.FileName;
        // читаем файл в строку
        string fileText = System.IO.File.ReadAllText(filename);
        textBox1.Text = fileText;
        MessageBox.Show("Файл открыт");
    }
}

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

0 / 0 / 0

Регистрация: 10.05.2013

Сообщений: 9

1

10.05.2013, 23:27. Показов 6805. Ответов 12


Добрый вечер! Я извиняюсь, если есть подобная тема, но нужно очень срочно. Проблема в том, что я перерыл весь интернет по поводу считывания и вывода данных из файла и в файл, соответственно, и почти разобрался, как это работает и реализовывается. Считывание с файла заработало(просто нужно было поменять свойство файла»Copy to Output» на «Сopy always»), но вот запись в файл так и не работает, перепробывал все варианты. Подскажите пожалуйста хоть что нибуть, может я опять упустил какую-нибудь мелочь. Заранее спасибо!

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



4 / 4 / 2

Регистрация: 13.12.2011

Сообщений: 46

10.05.2013, 23:41

2

Цитата
Сообщение от KerBerGen
Посмотреть сообщение

запись в файл так и не работает

Нужно сохранить в тот же файл или в другой?



0



Эксперт С++

3222 / 2481 / 429

Регистрация: 03.05.2011

Сообщений: 5,153

Записей в блоге: 20

10.05.2013, 23:50

3



0



0 / 0 / 0

Регистрация: 10.05.2013

Сообщений: 9

11.05.2013, 17:59

 [ТС]

4

Нужно сохранить в тот же файл или в другой?

Нет в другой файл, после выполнения неких действий, программа должна построчно дозаписывать данные в файл, при этом сохранять предыдущие данные.



0



dolte

Человек

326 / 200 / 63

Регистрация: 04.02.2013

Сообщений: 1,211

11.05.2013, 18:00

5

Пишем в файл

C#
1
2
3
4
5
6
7
8
{
FileInfo f = new FileInfo("Tournaments.txt");
StreamWriter writer = f.CreateText();
writer.WriteLine(textBox1.Text); //Откуда пишем
writer.Write(writer.NewLine);
writer.Close();
MessageBox.Show("Таблица успешно сохранена в: Tournaments.txt");
}

Добавить запись в файл

C#
1
2
3
4
5
6
7
{
StreamWriter writer = File.AppendText("Tournaments.txt");
writer.WriteLine (textBox1.Text); //Куда добавляем
writer.Write(writer.NewLine);
writer.Close();
MessageBox.Show ("Добавление текста прошло успешно");
}

Читаем файл

C#
1
2
3
4
5
6
7
8
9
{
StreamReader sr = File.OpenText("Tournaments.txt");
string text = null;
while ((text = sr.ReadLine()) != null)
{
textBox2.Text += text + "rn"; //Куда открываем файл
}
sr.Close();
}



1



0 / 0 / 0

Регистрация: 10.05.2013

Сообщений: 9

11.05.2013, 18:02

 [ТС]

6

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



0



dolte

Человек

326 / 200 / 63

Регистрация: 04.02.2013

Сообщений: 1,211

11.05.2013, 18:12

7

Цитата
Сообщение от KerBerGen
Посмотреть сообщение

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

Выше дополнил

C#
1
2
3
4
5
6
7
{
StreamWriter writer = File.AppendText("Tournaments.txt");
writer.WriteLine (textBox1.Text); //Куда добавляем
writer.Write(writer.NewLine);
writer.Close();
MessageBox.Show ("Добавление текста прошло успешно");
}

Добавлено через 8 минут
Ах да, перед открытием файла, текстбокс лучше чистить, вот так получится

C#
1
2
3
4
5
6
7
8
textBox1.Clear(); //Чистим текст бокс перед выводом содержимого файла.
StreamReader sr = File.OpenText ("Tournaments.txt");
string text = null;
while ((text = sr.ReadLine()) !=null)
{
textBox1.Text+=text+"rn";
}
sr.Close();



0



KerBerGen

0 / 0 / 0

Регистрация: 10.05.2013

Сообщений: 9

11.05.2013, 18:18

 [ТС]

8

Цитата
Сообщение от dolte
Посмотреть сообщение

Пишем в файл
Код C#
{
FileInfo f = new FileInfo(«Tournaments.txt»);
StreamWriter writer = f.CreateText();
writer.WriteLine(textBox7.Text);
writer.WriteLine(textBox8.Text);
writer.Write(writer.NewLine);
writer.Close();
MessageBox.Show(«Таблица успешно сохранена в: Tournaments.txt»);
}

Не записывает почему то совсем вот плевельный код же ведь:

C#
1
2
3
4
5
FileInfo otchet = new FileInfo("Otchet.txt");
            using (StreamWriter write_text = otchet.AppendText())
            {
                write_text.WriteLine(dano);
            }



0



dolte

Человек

326 / 200 / 63

Регистрация: 04.02.2013

Сообщений: 1,211

11.05.2013, 18:25

9

Цитата
Сообщение от KerBerGen
Посмотреть сообщение

Не записывает почему то совсем вот плевельный код же ведь:

C#
1
2
3
4
5
FileInfo otchet = new FileInfo("Otchet.txt");
            using (StreamWriter write_text = otchet.AppendText())
            {
                write_text.WriteLine(dano);
            }

Куда ты пихал код который я написал ?

Вот, например вешаем на кнопку, всё прекрасно работает

C#
1
2
3
4
5
6
7
8
9
void Button1Click(object sender, EventArgs e)
{
 FileInfo f = new FileInfo("Tournaments.txt");
 StreamWriter writer = f.CreateText();
 writer.WriteLine(textBox1.Text);
 writer.Write(writer.NewLine);
 writer.Close();
 MessageBox.Show("Таблица успешно сохранена в: Tournaments.txt");
 }



0



KerBerGen

0 / 0 / 0

Регистрация: 10.05.2013

Сообщений: 9

11.05.2013, 18:30

 [ТС]

10

Цитата
Сообщение от dolte
Посмотреть сообщение

Куда ты пихал код который я написал ?

В функции всё находится и вызывается из разных мест программы, но основной вызов тоже из кнопки, вот функция…

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
private void transition()
        {
            DateTime dt0 = new DateTime(dt.Year, dt.Month, dt.Day, 00, 45, 00);
            TimeSpan delta = dt0 - dt;
            dano += dt.ToShortDateString() + " " + delta + " " + Convert.ToString(count - balance) + " " + Convert.ToString(res) + " " + Convert.ToString((count - balance) - res) + " " + Convert.ToString(((float)res / (float)(count - balance)) * 100) + "%";// кол.вопр., правельных, не правельных, %
 
            FileInfo otchet = new FileInfo("Otchet.txt");
            using (StreamWriter write_text = otchet.CreateText())
            {
                write_text.WriteLine(dano);
                write_text.Write(write_text.NewLine);
                MessageBox.Show("Добавление текста прошло успешно");
            }
 
            this.Hide();
            Form3 f3 = new Form3(this.max - left, this.res, this.dt);
            f3.Show();
        }



0



dolte

Человек

326 / 200 / 63

Регистрация: 04.02.2013

Сообщений: 1,211

11.05.2013, 18:40

11

CreateText(» «) создает
AppendText(» «) добавляет

в цитате был код на создание и запись в файл
это не подходит:

C#
1
2
3
4
5
6
7
8
9
void Button1Click(object sender, EventArgs e)
{
 FileInfo f = new FileInfo("Tournaments.txt");
 StreamWriter writer = f.CreateText();
 writer.WriteLine(textBox1.Text);
 writer.Write(writer.NewLine);
 writer.Close();
 MessageBox.Show("Таблица успешно сохранена в: Tournaments.txt");
 }



0



0 / 0 / 0

Регистрация: 10.05.2013

Сообщений: 9

11.05.2013, 18:43

 [ТС]

12

Цитата
Сообщение от dolte
Посмотреть сообщение

CreateText(» «) создает
AppendText(» «) добавляет

Да я знаю всё это пытаю и так и сяк всё равно не хочет, но когда делаю дозапись в файл он ругается на то что уже там есть что то и не запускается программа. А мне именно дозапись нужна, ну всё равно не то ни другое не работает.



0



0 / 0 / 0

Регистрация: 10.05.2013

Сообщений: 9

15.05.2013, 01:06

 [ТС]

13

Всё спасибо большое за помощь, проблема разрешилась сама собой. Код действительно правельный, только почему то он не выводит в файл только в режиме разработчика при отладке программы, а запустил её в пользовательском режиме всё работает отлично! Ещё раз спасибо за помощь!



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

15.05.2013, 01:06

13

I am trying to display the content of a txt file.
I thought I should use RichTextBox for that method. What I’ve done was this. However it does not work.

public static byte[] ReadFile() {

        FileStream fileStream = new FileStream(@"help.txt", FileMode.Open, FileAccess.Read);
        byte[] buffer;
        try {
            int length = (int)fileStream.Length;  // get file length
            buffer = new byte[length];            // create buffer
            int count;                            // actual number of bytes read
            int sum = 0;                          // total number of bytes read

            // read until Read method returns 0 (end of the stream has been reached)
            while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                sum += count;  // sum is a buffer offset for next reading
        } finally {
            fileStream.Close();
        }
        return buffer;
    }

    private void richTextBox1_TextChanged(object sender, EventArgs e) {
        ReadFile();
    }

asked May 22, 2012 at 8:57

Sarp Kaya's user avatar

1

You’ve got a couple of problems here.

I suppose that richTextBox1_TextChanged is associated with the changed event of the RichTextBox you want to fill. This means that it isn’t executed unless you manually change the content of the RichTextBox itself.

Furthermore in the method you are calling a method (ReadFile) which read your file and return the content as a byte[], but the result get lost since you aren’t using it anyway.

Then even the way you are reading the file is not correct, since you are reading all the file at once (you are specifying to read the exact number of characters contained in the file), so the while loop isn’t needed.

I would attach to the load event of the form and write something like this:

public string FillRichText(string aPath)
{
    string content = File.ReadAllText(aPath);
    richTextBox1.Text = content;
}

private void Form1_Load(object sender, EventArgs e)
{
    FillRichText(@"help.txt");
}

You will need this line in the InitializeComponent() of your form:

this.Load += new System.EventHandler(this.Form1_Load);

answered May 22, 2012 at 9:15

Francesco Baruchelli's user avatar

I may be missing something but I don’t see where you are appending the result of your read to the textbox!

You are returning buffer but not using it anywhere.

answered May 22, 2012 at 9:01

Dave Lawrence's user avatar

Dave LawrenceDave Lawrence

3,8032 gold badges20 silver badges34 bronze badges

3

Do this:

  1. Have a button.

  2. On button click, call ReadFile(), convert byte[] received from ReadFile() to string and display in TextBox.

answered May 22, 2012 at 9:04

Falaque's user avatar

FalaqueFalaque

8762 gold badges12 silver badges27 bronze badges

4

Use this:

In the form’s constructor, write the following code:

public Form1()
{
    InitializeComponent(); // This should already be there by default

    string content = File.ReadAllText(@"help.txt");
    richTextBox1.Text = content;
}

This reads all the text from the given file in one go and assigns it to the rich text box. While you read the text in your method, you’re not converting the resulting byte array to a string and you’re also not assigning it to the rich text box. Simply reading the file won’t help.

Please remove the TextChanged event also: The TextChanged event is called every time the text in the rich text box is changed. This is also the case when setting a new value to the Text property, which would cause an infinite recursion. Also, this event is never called when the text doesn’t change in the first place, so you would have to enter text manually in the rich text box to fire this event.

answered May 22, 2012 at 9:04

Thorsten Dittmar's user avatar

Thorsten DittmarThorsten Dittmar

55.3k8 gold badges85 silver badges135 bronze badges

Change the method to the following and you don’t need rich textbox, a simple textbox can serve the purpose.

public void ReadFile() {

    TextReader reder = File.OpenText(@"help.txt");
    textBox1.Text = reder.ReadToEnd();        
}

answered May 22, 2012 at 9:08

Asif Mushtaq's user avatar

Asif MushtaqAsif Mushtaq

12.9k3 gold badges33 silver badges42 bronze badges

6

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (openFileDialog1.ShowDialog() == DialogResult.OK)   
        {
            label1.Text = openFileDialog1.FileName;
            richTextBox1.Text = File.ReadAllText(label1.Text);
        }
 }

answered Oct 17, 2016 at 7:13

Omobo Ebibote's user avatar

Понравилась статья? Поделить с друзьями:
  • Выборочное удаление точек восстановления windows 10
  • Вы используете универсальные драйверы windows uvc установите logitech
  • Вывод sql запроса в windows forms
  • Выборочная установка windows 7 без форматирования жесткого диска
  • Вы используете не подлинную версию windows 7