将文本框内容保存在文本文件中 C# [英] Saving TextBox content in a text file C#

查看:110
本文介绍了将文本框内容保存在文本文件中 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了这个表单,它允许我打开一个 txt 文件并将内容放入一个文本框.我希望能够修改文本框中写入的内容,然后使用 SaveFileDialog 保存它.这是我的代码

I created this form that allows me to open a txt file and puts the content in a TextBox. I want to be able to modify the content writing in the textbox and then save it using the SaveFileDialog. Here's my code

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;

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

        private void button1_Click(object sender, EventArgs e){
            if (openFileDialog1.ShowDialog() == DialogResult.OK){
                System.IO.StreamReader input = new
                System.IO.StreamReader(openFileDialog1.FileName);
                TextBox_stampa_contenuto.AppendText(input.ReadToEnd());
                input.Close();
            }
        }

        private void salva_file_Click(object sender, EventArgs e){
            saveFileDialog1.ShowDialog();
        }

        private void saveFileDialog1_FileOk(object sender, CancelEventArgs e){
            string name = saveFileDialog1.FileName;
            File.WriteAllText(name, TextBox_stampa_contenuto.Text);

        }
    }

}

当我运行它时,它可以完美地打开文件,但是在我修改它并尝试保存后它不起作用.内容保持不变.有办法解决吗?以及如何在写入模式而不是追加模式下将文本放入文本框中.谢谢.

When I run it works perfectly opening the file, but after I modify it and try to save it doesn't work. The content stays the same. There's a way to fix it? And also how can I put the text in the textbox in write mode and not in append mode. Thanks.

推荐答案

试试这个:

解决方案1:如果要将Textbox 的内容保存到TextFile 中,则需要检查SaveDialogDialogResult 返回类型.

Solution 1: if you want to Save the contents of Textbox into TextFile you need to check the DialogResult return type of the SaveDialog.

private void salva_file_Click(object sender, EventArgs e)
{
        DialogResult result = saveFileDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            string name = saveFileDialog1.FileName;
            File.WriteAllText(name, TextBox_stampa_contenuto.Text);
        }
 }

解决方案 2:如果您想将文件文本插入文本框而不附加,您需要将文件字符串分配到文本框 Text 属性.

Solution 2: if you want to Insert the File Text into Textbox whithout appending you need to Assign the File String into TextBox Text property.

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
  TextBox_stampa_contenuto.Text=System.IO.File.ReadAllText(openFileDialog1.FileName);      
}

这篇关于将文本框内容保存在文本文件中 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆