• 文件读写操作


    如图,点击选择文件则读取文件路径,读取时将文件内容显示到文本框中,写入时将文本框内容写入文件

    View Code
    namespace 文件操作
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }
    /// <summary>
    /// 选择文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button1_Click(object sender, EventArgs e)
    {
    OpenFileDialog open
    =new OpenFileDialog();
    open.Filter
    ="*.txt|*.txt"; //文件类型
    if (open.ShowDialog() == DialogResult.OK)
    {
    textBox1.Text
    = open.FileName;
    }
    }
    /// <summary>
    /// 读取文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button2_Click(object sender, EventArgs e)
    {
    if (textBox1.Text.Length <0)
    {
    return;
    }
    Stream stream
    =new FileStream(textBox1.Text, FileMode.Open, FileAccess.Read);
    using (StreamReader reader
    =new StreamReader(stream, Encoding.Default))
    {
    string pp
    ="";
    while (reader.Peek() >-1)
    {
    pp
    += reader.ReadLine();
    }
    richTextBox1.Text
    = pp;

    }
    }
    /// <summary>
    /// 写入文件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button3_Click(object sender, EventArgs e)
    {
    Stream stream
    =new FileStream(textBox1.Text, FileMode.Create, FileAccess.Write);
    StreamWriter writer
    =new StreamWriter(stream, Encoding.Default);
    writer.WriteLine(richTextBox1.Text);

    }
    }
    }
  • 相关阅读:
    嵌入式工程师为何不用学习C++语言?
    汽车电子基础知识
    为什么寄存器比存储器快?
    数字信号和模拟信号
    JLink和JTag的区别
    C++中static关键字作用总结
    所谓高情商,就是会说话
    汽车电子缩略语及术语
    卷积
    算法整理
  • 原文地址:https://www.cnblogs.com/happygx/p/1982059.html
Copyright © 2020-2023  润新知