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 字节流的临时存储 ...
随机推荐
- JQuery Ajax 的简单使用
简单判断用户名存在不存在,如果数据库存在此用户名,提示不能注册 前台代码如下: <!DOCTYPE html> <html lang="en"> <h ...
- iOS 开发之 Xcode6 打包生成ipa给测试
Xcode 6正式版Version 6.0.1 (6A317)已经放出Mac AppStore,之前为了体验swift也安装过beta版,但是并没有注意到6系Xcode对于导出ipa的变化,更新正式版 ...
- CodeForces 429 B Working out(递推dp)
题目连接:B. Working out 我想了很久都没有想到怎么递推,看了题解后试着自己写,结果第二组数据就 wa 了,后来才知道自己没有判选择的两条路径是否只是一个交点. 大概思路是:先预处理出每个 ...
- XMLHttpRequest cannot load – Origin is not allowed by Access-Control-Allow-Origin.
报错:跨域 XMLHttpRequest cannot load http://localhost:8080/yxt-admin/admin/store. No 'Access-Control-Al ...
- css3中的过渡(transition)
css3 transition(过渡)1.语法: transition:[ transition-property ] || [ transition-duration ] || [ transiti ...
- Java中for循环遍历List的两种方法
我们平常使用的方法: List<WebElement> element = driver.findElements(By.tagName("input")); ...
- 使用 Subversion (SVN) 的方式来访问 Github(转)
[转至]:http://www.open-open.com/lib/view/open1340760267717.html
- OneProxy与其它数据库中间件的对比
OneProxy 优点 性能 缺点 闭源,被商业公司掌控,到时候随别人蹂躏 可维护性极差,缺乏友好的出错信息,光维护这个环节就被他人掌控 定价不明 有没有这样的公司? 大到10wtps,但是没人能理解 ...
- linux笔记:linux常用命令-链接命令
文件处理命令:ln(创建链接文件) ln -s 源文件 链接文件 需要源文件已经建立,执行链接文件就是执行源文件. 软链接文件的特点: 1.类似于windows中快捷方式的作用: 2.它的文件类型是 ...
- Python 练习 21
#!/usr/bin/python # -*- coding: UTF-8 -*- h = 0 leap = 1 from math import sqrt from sys import stdou ...