C# 文件与目录的基本操作(System.IO)

1. 文件操作

C# 文件与目录的基本操作(System.IO)

/// <summary>
/// 文件读写操作
/// 为简化代码供大家学习,暂不考虑捕捉异常
/// </summary>
public partial class TestIO : DevComponents.DotNetBar.Office2007Form
{
    public TestIO()
    {
        InitializeComponent();
    }
 
    /// <summary>
    /// 创建文件
    /// </summary>
    private void btnCreateFile_Click(object sender, EventArgs e)
    {
        string path = Application.StartupPath + @"\Test.txt";
        FileStream fs = new FileStream(path, FileMode.Create);
        StreamWriter sw = new StreamWriter(fs);
        sw.WriteLine("This is a test file.");
        sw.WriteLine("This is second line.");
        sw.Close();
        fs.Close();
 
        // 也可以这样创建 StreamWriter
        // StreamWriter sw = File.CreateText(path);
    }
 
    /// <summary>
    /// 读取文件
    /// </summary>
    private void btnReadFile_Click(object sender, EventArgs e)
    {
        string path = Application.StartupPath + "\\Test.txt";
        textBoxX1.Text = string.Empty;
        if (File.Exists(path))
        {
            FileStream fs = new FileStream(path, FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            // 也可以这样创建 StreamReader
            // File.OpenText(path);
            string str = string.Empty;
            while (true)
            {
                str = sr.ReadLine();
                if (!string.IsNullOrEmpty(str))
                {
                    textBoxX1.Text += str + "\r\n";
                }
                else
                {
                    sr.Close();
                    fs.Close();
                    break;
                }
            }
        }
        else
        {
            MessageBox.Show("指定的路径下不存在此文件!");
        }
    }
 
    /// <summary>
    /// 追加文件内容
    /// </summary>
    private void btnAppendFile_Click(object sender, EventArgs e)
    {
        string path = Application.StartupPath + "\\Test.txt";
        FileStream fs = new FileStream(path, FileMode.Append);
        StreamWriter sw = new StreamWriter(fs);
        // 也可以这样创建 StreamReader
        // StreamWriter sw = File.AppendText(path);
        sw.WriteLine("This is three line.");
        sw.Close();
        fs.Close();
    }
 
    /// <summary>
    /// 复制文件
    /// </summary>
    private void btnCopyFile_Click(object sender, EventArgs e)
    {
        string oldPath = Application.StartupPath + "\\Test.txt";
        string newPath = Application.StartupPath + "\\TestClone.txt";
        File.Copy(oldPath, newPath);
    }
 
    /// <summary>
    /// 删除文件
    /// </summary>
    private void btnDeleteFile_Click(object sender, EventArgs e)
    {
        string path = Application.StartupPath + "\\TestClone.txt";
        File.Delete(path);
    }
 
 
    /// <summary>
    /// 移动文件
    /// </summary>
    private void btnMoveFile_Click(object sender, EventArgs e)
    {
        string oldPath = Application.StartupPath + "\\Test.txt";
        // 移动文件的同时也可以使用新的文件名
        string newPath = "d:\\NewTest.txt";
        File.Move(oldPath, newPath);
    }
 
    /// <summary>
    /// 创建目录
    /// </summary>
    private void btnCreateDirectory_Click(object sender, EventArgs e)
    {
        string path1 = "d:\\Jason1";
        // 创建目录 Jason1
        DirectoryInfo dDepth1 = Directory.CreateDirectory(path1);
        // dDepth2 指向 dDepth1 创建的子目录 Jason2
        DirectoryInfo dDepth2 = dDepth1.CreateSubdirectory("Jason2");
        // 设置应用程序当前的工作目录为 dDepth2 指向的目录
        Directory.SetCurrentDirectory(dDepth2.FullName);
        // 在当前目录创建目录 Jason3
        Directory.CreateDirectory("Jason3");
    }
 
    private void btnDeleteDirectory_Click(object sender, EventArgs e)
    {
        string path = "d:\\Jason1";
        DeleteDirectory(path);
    }
 
    /// <summary>
    /// 删除目录及其所有子目录,文件
    /// </summary>
    private static void DeleteDirectory(string path)
    {
        if (Directory.Exists(path))
        {
            foreach (string str in Directory.GetFileSystemEntries(path))
            {
                if (File.Exists(str))
                {
                    File.Delete(str);
                }
                else
                {
                    DeleteDirectory(str);
                }
            }
            Directory.Delete(path);
        }
        else
        {
            MessageBox.Show("该目录不存在!");
        }
    }
 
    private void btnCopyDirectory_Click(object sender, EventArgs e)
    {
        string sourcePath = "d:\\Jason1";
        string targetPath = "d:\\Jason2";
        CopyDirectory(sourcePath, targetPath);
    }
 
    /// <summary>
    /// 复制目录及其所有内容
    /// </summary>
    /// <param name="sourcePath">源目录</param>
    /// <param name="targetPath">目标目录</param>
    private void CopyDirectory(string sourcePath, string targetPath)
    {
        // 该字符用于在反映分层文件系统组织的路径字符串中分隔目录级别(msdn)
        // 在windows系统下实质上是为目录路径加上"\\"
        if (targetPath[targetPath.Length - 1] != Path.DirectorySeparatorChar)
        {
            targetPath += Path.DirectorySeparatorChar;
        }
        // 目标目录不存在则创建之
        if (!Directory.Exists(targetPath))
        {
            Directory.CreateDirectory(targetPath);
        }
        // 获取文件系统(含目录和文件)
        string[] fileList = Directory.GetFileSystemEntries(sourcePath);
        foreach (string fileName in fileList)
        {
            if (Directory.Exists(fileName))
            {
                // Path.GetFileName(fileName) 可取出最后一个分级目录名或文件名
                CopyDirectory(fileName, targetPath + Path.GetFileName(fileName));
            }
            else
            {
                // true 为可覆盖
                File.Copy(fileName, targetPath + Path.GetFileName(fileName), true);
            }
        }
    }
}
上一篇:笔试题&面试题:设计一个复杂度为n的算法找到单向链表倒数第m个元素


下一篇:Insights直播回顾——手语服务,助力沟通无障碍