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. iOS - UIDatePicker

    前言 NS_CLASS_AVAILABLE_IOS(2_0) __TVOS_PROHIBITED @interface UIDatePicker : UIControl <NSCoding> ...

  2. Redis基础知识之—— 5个必须了解的事情【★★★★★】

    一.掌控储存在Redis中的所有键 数据库的主要功能是储存数据,但是对于开发者来说,因为应用程序需求或者数据使用方法的改变,忽略存储在数据库中的某些数据是非常正常的,在Redis中同样如此.你可能忽视 ...

  3. 让你分分钟读懂CPU架构及芯片厂商

    CPU架构是CPU厂商给属于同一系列的CPU产品定的一个规范,主要目的是为了区分 不同类型CPU的重要标示.目前市面上的CPU指令集分类主要分有两大阵营,一个是intel.AMD为首的复杂指令集CPU ...

  4. 百度地图-marker拖拉,右键菜单

    marker拖拉,修改经纬度. //创建Map实例 var map = new BMap.Map("allmap"); var point=new BMap.Point(104.0 ...

  5. 编译maxscale

    编译maxscale,需要依赖mariadb版本的MySQL.有自己的版本就是任性啊

  6. 【转】 C++中delete和delete[]的区别

    一直对C++中的delete和delete[]的区别不甚了解,今天遇到了,上网查了一下,得出了结论.做个备份,以免丢失. C++告诉我们在回收用 new 分配的单个对象的内存空间的时候用 delete ...

  7. Lecture Notes: Macros

    原论文链接失效,特在这里保存一份 http://www.apl.jhu.edu/~hall/Lisp-Notes/Macros.html Lisp functions take Lisp values ...

  8. robotframework笔记1

    机器人框架是一个基于Python的,可扩展的关键字驱动的自动化测试最终到终端的验收测试和验收测试驱动开发(ATDD)框架.它可用于检测分布式异类应用程序,其中,验证要求感人几种技术和接口. 下面列出了 ...

  9. hdu 4405Aeroplane chess(概率DP)

    Aeroplane chess Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) ...

  10. 给文本标签UILabel添加长按复制功能

    http://www.111cn.net/sj/iOS/104236.htm http://blog.csdn.net/lrenjun/article/details/12582927 自定义一个可复 ...