1. 文件操作

/// <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);
            }
        }
    }
}

C# 文件与目录的基本操作(System.IO)的更多相关文章

  1. c# 命名空间之System.IO(继承关系)

    System.IO 命名空间包含允许:读写文件.数据流的类型以及提供基本文件和目录支持的类型. 在这个命名空间中主要的类有: 字节流:Stream.BufferedStream.MemoryStrea ...

  2. 命名空间System.IO

    基本介绍:System.IO 命名空间提供读写文件和数据流的类型.基本文件和目录支持的类型. 原文:http://blog.sina.com.cn/s/blog_48a45b950100erhz.ht ...

  3. System.IO命名空间下常用的类

    System.IO System.IO.Directory 目录 System.IO.Path 文件路径(包含目录和文件名) System.IO.FileInfo 提供创建.复制.删除.移动和打开文件 ...

  4. System.IO.Path 文件名、路径、扩展名 处理

    string filePath =@"E:/Randy0528/中文目录/JustTest.rar"; 更改路径字符串的扩展名.System.IO.Path.ChangeExten ...

  5. System.IO.Path 文件名、路径、扩展名处理

    string filePath =@"E:/Randy0528/中文目录/JustTest.rar"; 更改路径字符串的扩展名.System.IO.Path.ChangeExten ...

  6. System.IO之内存映射文件共享内存

    内存映射文件是利用虚拟内存把文件映射到进程的地址空间中去,在此之后进程操作文件,就 像操作进程空间里的地址一样了,比如使用c语言的memcpy等内存操作的函数.这种方法能够很好的应用在需要频繁处理一个 ...

  7. System.IO.Directory.Delete目录删除

    在程序运行的时候,如果直接获取一个目录路径,然后执行删除(包括子目录及文件): System.IO.Directory.Delete(path,true); 或者 System.IO.Director ...

  8. IIS目录下文件共享后System.IO.File.Exists返回false

    场景:在iis目录下,因为特殊需要共享一个文件夹,给到其他的技术人员访问,突然发现小小的操作,搞“大”了,使用 string path = Server.MapPath("~/file/te ...

  9. C# System.IO和对文件的读写操作

      System.IO命名空间中常用的非抽象类 BinaryReader 从二进制流中读取原始数据 BinaryWriter 从二进制格式中写入原始数据 BufferedStream 字节流的临时存储 ...

随机推荐

  1. [转载] C++ STL string的Copy-On-Write技术

    原文: http://coolshell.cn/articles/12199.html stl的string是经过严格优化的, 深入理解对以后编程过程中应用string非常有益处, 感谢左耳朵耗子的精 ...

  2. sscanf的用法(转)

    队长做上海邀请赛的I题时遇到一个棘手的问题,字符串的处理很麻烦,按传统的gets全部读入的话还要做N多处理,太浪费时间. 回来之后搜了一下sscanf的用法发现可以很好的解决这一类问题,各种百度,转来 ...

  3. Java中ArrayDeque,栈与队列

    package ch8; import java.util.*; /** * Created by Jiqing on 2016/11/27. */ public class ArrayDequeSt ...

  4. Centos升级Python及pip

    因为CentOS系统中旧版本的Python已被深度依赖,所以不能卸载原有的Python,只能全新安装. 1.从官网下载: wget https://www.python.org/ftp/python/ ...

  5. JavaSE复习_11 IO流复习

    △FileReader是使用默认码表读取文件, 如果需要使用指定码表读取, 那么可以使用InputStreamReader(字节流,编码表)    FileWriter是使用默认码表写出文件, 如果需 ...

  6. Android 新手引导

    关于这个Demo的写法很多 我也献上一段 效果图如下 上代码 MainActivity public class MainActivity extends Activity { // public L ...

  7. SonarLint插件的安装与使用

    注意:版本要求Eclipse(4.2,3.8)以上,Java3.1.2,JavaScript 2. 一.SonarLint插件的安装方式 1.安装方式一:在线安装 1)Eclipse工具栏选择Help ...

  8. LTIB常用命令1

    下面再写一点ltib的常用命令参数吧,虽然觉得对其编译内核和文件系统流程有了一定了解,但是对其命令参数用过的还不是很多,可以说是不甚了解,下面介绍一些,希望有用: 首先一个比较有用的命令参数就是hel ...

  9. xmpp怎么让群主踢人?

    不知道其他语言版的xmpp,framework是怎样的,就OC版提供的xmpp框架来说,它只提供了邀请其他用户进群的API: - (void)inviteUser:(XMPPJID *)jid wit ...

  10. 【MRPT】【icp-slam-live】Vs2013+ cmake3.6.1 + mrpt1.4.0+opencv2.9.4+wxWidget3.0.2环境配置

    Win10下Vs2013 + cmake3.6.1 + mrpt1.4.0+opencv2.9.4+wxWidget3.1.0环境配置 所接触过的最令我崩溃的环境配置.之前没有考虑到vs2013 20 ...