您的位置:首页 > 编程语言 > C#

C# 文件与目录的基本操作

2016-11-10 15:50 148 查看
1. 文件的创建和写入

public void BtnCreateFile_Click()
{
string path = Application.dataPath + @"\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);
}

2.读取文件,文件内容
/// <summary>
/// 读取文件
/// </summary>
public void b移动文件tnReadFile_Click()
{
string path = Application.dataPath + "\\Test.txt";
text.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))
{
text.text += str + "\r\n";
}
else
{
sr.Close();
fs.Close();
break;
}
}
}
else
{
text.text = "指定的路径下不存在此文件!";
}
}

3. 追加文件内容
/// <summary>
/// 追加文件内容
/// </summary>
public void BtnAppendFile_Click()
{
string path = Application.dataPath + "\\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();
}4.复制文件
/// <summary>
/// 复制文件
/// </summary>
public void BtnCopyFile_Click()
{
string oldPath = Application.dataPath + "\\Test.txt";
string newPath = Application.dataPath + "\\TestClone.txt";
File.Copy(oldPath, newPath);
}5.删除文件
/// <summary>
/// 删除文件
/// </summary>
public void BtnDeleteFile_Click()
{
string path = Application.dataPath + "\\TestClone.txt";
File.Delete(path);
}6.移动文件
/// <summary>
/// 移动文件
/// </summary>
public void BtnMoveFile_Click()
{
string oldPath = Application.dataPath + "\\Test.txt";
// 移动文件的同时也可以使用新的文件名
string newPath = "C:\\NewTest.txt";
File.Move(oldPath, newPath);
}7.创建目录
/// <summary>
/// 创建目录
/// </summary>
public void BtnCreateDirectory_Click()
{
string path1 = "C:\\Jason1";
// 创建目录 Jason1
DirectoryInfo dDepth1 = Directory.CreateDirectory(path1);
// dDepth2 指向 dDepth1 创建的子目录 Jason2
DirectoryInfo dDepth2 = dDepth1.CreateSubdirectory("Jason2");
// 设置应用程序当前的工作目录为 dDepth2 指向的目录
Directory.SetCurrentDirectory(dDepth2.FullName);
// 在当前目录创建目录 Jason3
Directory.CreateDirectory("Jason3");
}
8.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: