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. Redis脚本插件之————执行Lua脚本示例

    Redis在2.6推出了脚本功能,允许开发者使用Lua语言编写脚本传到Redis中执行.使用脚本的好处如下: 1.减少网络开销:本来5次网络请求的操作,可以用一个请求完成,原先5次请求的逻辑放在red ...

  2. c++ 临时变量

    C++的临时变量 它们是被神所遗弃的孩子,没有人见过它们,更没有人知道它们的名字.它们命中注定徘徊于命运边缘高耸的悬崖和幽深的深渊之间,用自己短暂的生命抚平了生与死之间的缝隙.譬如朝露,却与阳光无缘. ...

  3. PHP 用文件流方式展示图片

    public function index(){ $img = 'http://img.pf.loc/static/images/2016/05/24/21d98edf98bd6c30afe1c838 ...

  4. OpenGL的gluPerspective透视投影变换函数详解[转]

    函数原型void gluPerspective(GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar) 首先得设置gluPersp ...

  5. myeclipse黑色主题怎么还原

    删除workspace-->.metadata-->.plugins-->org.eclipse.core.runtime

  6. Apache mod_jk

    http://tomcat.apache.org/connectors-doc/generic_howto/loadbalancers.html http://tomcat.apache.org/co ...

  7. weblogic 下载安装部署说明

    http://blog.csdn.net/gaofuqi/article/details/36870887/ http://jingyan.baidu.com/article/d8072ac45f57 ...

  8. crontab在一秒内刷新多次导致部分脚本不生效的问题分析

    版权声明:本文由康中良原创文章,转载请注明出处: 文章原文链接:https://www.qcloud.com/community/article/182 来源:腾云阁 https://www.qclo ...

  9. python 练习 30

    Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对象是很容易的.本章节我们将详细介绍Python的面向对象编程. 如果你以前没有接触过面向对象的编程语言,那你 ...

  10. jquery 设置css样式

       $("#61dh a").css('color', 多个样式属性 var divcss = { background: '#EEE', width: '478px', mar ...