c# winform中如何实现文件操作

   2024-09-30 3100
核心提示:在C# WinForm中,可以使用.NET Framework提供的类库来实现文件操作。这里有一些常见的文件操作示例:读取文本文件:using System

在C# WinForm中,可以使用.NET Framework提供的类库来实现文件操作。这里有一些常见的文件操作示例:

读取文本文件:
using System;using System.IO;namespace FileOperation{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void btnReadFile_Click(object sender, EventArgs e)        {            string filePath = "example.txt";            if (File.Exists(filePath))            {                using (StreamReader sr = new StreamReader(filePath))                {                    string content = sr.ReadToEnd();                    MessageBox.Show(content);                }            }            else            {                MessageBox.Show("文件不存在!");            }        }    }}
写入文本文件:
private void btnWriteFile_Click(object sender, EventArgs e){    string filePath = "output.txt";    string content = "Hello, World!";    using (StreamWriter sw = new StreamWriter(filePath))    {        sw.WriteLine(content);    }    MessageBox.Show("文件已写入!");}
创建文件夹:
private void btnCreateFolder_Click(object sender, EventArgs e){    string folderPath = @"C:\example_folder";    if (!Directory.Exists(folderPath))    {        Directory.CreateDirectory(folderPath);        MessageBox.Show("文件夹已创建!");    }    else    {        MessageBox.Show("文件夹已存在!");    }}
删除文件夹:
private void btnDeleteFolder_Click(object sender, EventArgs e){    string folderPath = @"C:\example_folder";    if (Directory.Exists(folderPath))    {        Directory.Delete(folderPath, true); // 第二个参数表示是否删除子目录和文件        MessageBox.Show("文件夹已删除!");    }    else    {        MessageBox.Show("文件夹不存在!");    }}
遍历文件夹:
private void btnListFiles_Click(object sender, EventArgs e){    string folderPath = @"C:\example_folder";    if (Directory.Exists(folderPath))    {        string[] files = Directory.GetFiles(folderPath);        foreach (string file in files)        {            MessageBox.Show(file);        }    }    else    {        MessageBox.Show("文件夹不存在!");    }}

这些示例展示了如何在C# WinForm应用程序中执行基本的文件操作。你可以根据需要修改这些代码以满足你的需求。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号