日期:2014-05-18  浏览次数:20767 次

用C#搞一个窗体的,能读写TXT文件的,谢谢了
用C#搞一个窗体的,能读写TXT文件的,谢谢了,越快越好

------解决方案--------------------
form添加openFileDialog,添加按钮点击事件如下: 
private void button1_Click(object sender, EventArgs e)
{
//获取曲线数据文件
this.openFileDialog1.Filter = "Txt文件(*.txt)|*.txt";//设置只能打开TXT文件
this.openFileDialog1.Title = "导入TXT";
DialogResult result = this.openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string file_name = this.openFileDialog1.FileName;//保存文件路径
if (file_name != "")
{
this.filePathTe.Text = file_name;

}

}
}
------解决方案--------------------
读:
C# code

            openFile.ShowDialog();
            strFileName = openFile.FileName;
            if (strFileName == "") return;
            //读取txt文件
              StreamReader sr = new StreamReader(strFileName,System.Text.Encoding.Default);
            string strText = sr.ReadToEnd();
            sr.Close();
            sr.Dispose();
            textBox1=strText ;

------解决方案--------------------

C# code

public class TextForm : Form
{
    TextBox _edit;
    string _filename;
    bool _dirty;

    public TextForm()
    {
        _edit = new TextBox();
        _edit.Dock = DockStyle.Fill;
        _edit.TextChanged = (sender, e) => { _dirty = true; };
        this.Controls.Add(_edit);
    }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        OpenFileDialog dlg = new OpenFileDialog();
        dlg.Filter = "文本文件|*.txt";

        if (dlg.ShowDialog() == DialogResult.OK)
        {
            _filename = dlg.FileName;
            _edit.Text = System.IO.File.ReadAllText(_filename);
            _dirty = false;
        }
    }

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        if (!e.Cancel && _dirty)
        {
            DialogResult dr = MessageBox.Show("文件已更改,是否保存?", "确认",
                MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

            if (dr == DialogResult.Yes)
            {
                if (_filename == null)
                {
                    SaveFileDialog dlg = new SaveFileDialog();
                    dlg.Filter = "文本文件|*.txt";
                    if (dlg.ShowDialog() == DialogResult.OK)
                        _filename = dlg.FileName;
                }

                if (_filename != null)
                {
                    System.IO.File.WriteAllText(_filename, _edit.Text);
                }
            }
            else if (dr == DialogResult.Cancel)
                e.Cancel = true;
        }
    }

}