C# 文件与目录的基本操作(System.IO)
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)的更多相关文章
- c# 命名空间之System.IO(继承关系)
System.IO 命名空间包含允许:读写文件.数据流的类型以及提供基本文件和目录支持的类型. 在这个命名空间中主要的类有: 字节流:Stream.BufferedStream.MemoryStrea ...
- 命名空间System.IO
基本介绍:System.IO 命名空间提供读写文件和数据流的类型.基本文件和目录支持的类型. 原文:http://blog.sina.com.cn/s/blog_48a45b950100erhz.ht ...
- System.IO命名空间下常用的类
System.IO System.IO.Directory 目录 System.IO.Path 文件路径(包含目录和文件名) System.IO.FileInfo 提供创建.复制.删除.移动和打开文件 ...
- System.IO.Path 文件名、路径、扩展名 处理
string filePath =@"E:/Randy0528/中文目录/JustTest.rar"; 更改路径字符串的扩展名.System.IO.Path.ChangeExten ...
- System.IO.Path 文件名、路径、扩展名处理
string filePath =@"E:/Randy0528/中文目录/JustTest.rar"; 更改路径字符串的扩展名.System.IO.Path.ChangeExten ...
- System.IO之内存映射文件共享内存
内存映射文件是利用虚拟内存把文件映射到进程的地址空间中去,在此之后进程操作文件,就 像操作进程空间里的地址一样了,比如使用c语言的memcpy等内存操作的函数.这种方法能够很好的应用在需要频繁处理一个 ...
- System.IO.Directory.Delete目录删除
在程序运行的时候,如果直接获取一个目录路径,然后执行删除(包括子目录及文件): System.IO.Directory.Delete(path,true); 或者 System.IO.Director ...
- IIS目录下文件共享后System.IO.File.Exists返回false
场景:在iis目录下,因为特殊需要共享一个文件夹,给到其他的技术人员访问,突然发现小小的操作,搞“大”了,使用 string path = Server.MapPath("~/file/te ...
- C# System.IO和对文件的读写操作
System.IO命名空间中常用的非抽象类 BinaryReader 从二进制流中读取原始数据 BinaryWriter 从二进制格式中写入原始数据 BufferedStream 字节流的临时存储 ...
随机推荐
- web发展总结
- odoo关联表查询方法
testinfo=self.env['product.attribute.value'].search([('product_ids.product_tmpl_id','=',2047)]) for ...
- [CSS] vertical-align
原文地址: http://www.zhangxinxu.com/wordpress/2010/05/%E6%88%91%E5%AF%B9css-vertical-align%E7%9A%84%E4%B ...
- Yum常用命令及Yum中文手册
转自:http://blog.csdn.net/huangbiao86/article/details/6646471 Yum配置文件位于/etc/yum.conf和/etc/yum.repos.d/ ...
- c++程序编码
c++程序中涉及到中文字符的输入输出以及其他操作经常会出现乱码.乱码主要是由于程序的源文件编码.可执行文件编码以及程序运行环境的编码不匹配导致.比如,c++源程序文件编码为GB18030, 在源程序中 ...
- 主成分分析(PCA)原理及R语言实现
原理: 主成分分析 - stanford 主成分分析法 - 智库 主成分分析(Principal Component Analysis)原理 主成分分析及R语言案例 - 文库 主成分分析法的原理应用及 ...
- ajax 动态获取json的例子
1.前台脚本: //用于切换图片列表的ajax function changePhoto(title,hotelId){ $.ajax({ contentType: "application ...
- 发布完ArcGIS地图服务后,服务未启动成功
今天下午更新地图服务后,服务未启动成功.出来的弹出框警告问题目前应该是ArcGIS Server出了问题,打开ArcCatalog目录,查看GIS服务器下localhost下的服务,只要是今天发布的服 ...
- js判断是不是chrome浏览器
方法一: var isChrome = window.navigator.userAgent.indexOf("Chrome"); <script> var isChr ...
- [Java] 数据库连接管理类
package com.wdcloud.monitoring.common; /** * @Description: TODO * @date: 2015��11��19�� ����10:23:16 ...