版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创!
恰饭广告
实现效果:
实现代码:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; namespace IOTest { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //目录遍历 listBox1.Items.Clear(); DirectoryInfo di = new DirectoryInfo("c:/"); foreach (DirectoryInfo folder in di.GetDirectories()) { if ((folder.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden && (folder.Attributes & FileAttributes.System) != FileAttributes.System) { // Attribute&FileAttributes.Hidden 判断是否为隐藏目录 //Attributes & FileAttributes.System 判断是否为系统文件 this.listBox1.Items.Add(folder.Name); } } } private void button2_Click(object sender, EventArgs e) { //遍历文件 listBox2.Items.Clear(); DirectoryInfo di = new DirectoryInfo("c:/"); foreach (FileInfo file in di.GetFiles()) { if ((file.Attributes & FileAttributes.Hidden) != FileAttributes.Hidden && (file.Attributes & FileAttributes.System) != FileAttributes.System) { // Attribute&FileAttributes.Hidden 判断是否为隐藏目录 //Attributes & FileAttributes.System 判断是否为系统文件 this.listBox2.Items.Add(file.Name); } } } private void button6_Click(object sender, EventArgs e) { //创建目录 if (Directory.Exists(@"c:/test/233")) { MessageBox.Show("目录已存在"); } else { Directory.CreateDirectory(@"c:/test/233"); MessageBox.Show("目录已创建"); } } private void button7_Click(object sender, EventArgs e) { //创建文件 StreamWriter sw = new StreamWriter("c:/test/text.txt"); sw.Close(); MessageBox.Show("文件已创建"); } private void button3_Click(object sender, EventArgs e) { //文件写入 StreamWriter sw1 = new StreamWriter("c:/test/text.txt", false, Encoding.GetEncoding("GB2312")); sw1.Write(richTextBox1.Text); sw1.Close(); } private void button4_Click(object sender, EventArgs e) { //文件追加写入 FileStream fs = File.OpenWrite("c:/test/text1.txt"); Encoding encode = Encoding.UTF8; byte[] b = encode.GetBytes(richTextBox2.Text); fs.Position = fs.Length; fs.Write(b, 0, b.Length); fs.Close(); } private void button5_Click(object sender, EventArgs e) { //文件读取 StreamReader sr = new StreamReader("c:/test/text1.txt"); string line; while ((line=sr.ReadLine())!=null) { richTextBox3.Text=line; } } } }
注意:using system.io;
文件的写入和读取应增加异常处理
原文链接:https://www.idaobin.com/archives/991.html
让我恰个饭吧.ヘ( ̄ω ̄ヘ)
恰饭广告