目录
1.文件
.NET Framework提供了File类和FileInfo类,以方便在程序中直接操作文件。File和FileInfo类位于System.IO命名空间,都可以用来实现创建、复制、移动、打开文件等操作。File类和FileInfo类与Directory类和DirectoryInfo类的工作方式相似。File类是一个静态类,可直接调用其方法成员,File类是用来操作文件的,它是一个静态类,其成员也是静态的,通过类名.类成员的形式调用其属性和方法。FileInfo类不是静态类,需要先创建实例。
因此要使用FileInfo类,必须先实例化一个FileInfo对象。
- FileInfo类的常用方法与File类基本相同。File类和Directory类适合对不同的对象进行单一的处理。此种特殊情况下,静态方法的调用速度比较快,不用进行实例化。
- FileInfo类和DirectoryInfo类适合用于对同一文件或文件夹进行多种操作的情况。此种情况下,实例化后的对象不需要每次都寻找文件,可以直接对该文件进行操作。
1.1 File文件类
File类是一个静态类,可直接调用其方法成员。File类的常用方法如下表
常用方法 | 作用介绍 |
---|---|
Open() | 打开文件 |
Create() | 创建文件 |
Copy() | 复制文件 |
Delete() | 删除文件 |
Exists() | 判断文件是否存在 |
Move() | 移动文件 |
Replace() | 替换文件 |
AppendAllText() | 新建文件并添加文本 |
ReadAllText() | 打开并读取文本内容 |
File类的用法举例:
//设置所要创建文件的绝对路径
string path = @"d:\test.txt";
//以路径为参数创建文件
File.Create(path);
运行上述程序代码段,会在d盘根目录下创建一个test.txt文件
File类中获取或设置文件信息的的常用方法如下表:
属性或方法 | 使用介绍 |
---|---|
DateTime GetCreationTime(string path) | 返回指定文件或目录的创建日期和时间 |
DateTime GetLastAccessTime(string path) | 返回上次访问指定文件或目录的日期和时间 |
DateTime GetLastWriteTime(string path) | 返回上次写入指定文件或目录的日期和时间 |
void SetCreationTime(string path, DateTime creationTime) | 设置创建该文件的日期和时间 |
void SetLastAccessTime(string path, DateTime lastAccessTime) | 设置上次访问指定文件的日期和时间 |
void SetLastWriteTime(string path, DateTime lastWriteTime) | 设置上次写入指定文件的日期和时间 |
1.2 FileInfo文件信息类
FileInfo类不是静态类,需要先创建实例。
文件信息类FileInfo与File类不同,它虽然也提供类创建、复制、删除、移动和打开文件的方法,并且帮助创建FileStream对象,但是它提供的仅仅是实例方法
FileInfo类的常用字段和方法见下表:
常用字段 | 使用介绍 |
---|---|
Name | 提取字段名 |
Directory | 所属目录 |
Exists | 是否存在(继承自父类FileSystemInfo) |
Extension | 文件扩展名 |
Length | 文件长度 |
IsReadOnly | 是否为只读 |
常用方法 | 使用介绍 |
---|---|
Open() | 打开文件 |
Create() | 创建文件 |
CopyTo() | 复制到新文件 |
Delete() | 删除文件 |
MoveTo() | 移动文件 |
Replace() | 替换文件 |
EnCrypt() | 加密文件 |
Decrypt() | 解密文件 |
2.文件夹
2.1 Directory文件夹
Directory类也是对文件夹进行操作的,它是一个静态类,不能创建该类的实例,直接通过类名.类成员的形式调用其属性和方法。
Directory类省去了创建类实例的步骤,其他操作也与Directoryinfo类似。
2.2 DirectoryInfo文件夹
DirectoryInfo类不是静态类,需要先创建实例。
DirectoryInfo文件夹类的常用属性和方法:
属性或方法 | 使用介绍 |
---|---|
Exists | 只读属性,获取指示目录是否存在的值 |
Name | 只读属性,获取Directorylnfo实例的目录名称 |
Parent | 只读属性,获取指定的子目录的父目录 |
Root | 只读属性,获取目录的根部分 |
void Create() | 创建目录 |
void Delete() | 如果目录中为空,则将目录删除 |
void Delete(bool recursive) | 指定是否删除子目录和文件,如果recursive 参数的值为True,则删除,否则不删除 |
DirectoryInfo[] GetDirectories() | 返回当前目录的子目录 |
DirectoryInfo[] GetDirectories(string searchPattern) | 返回匹配给定的搜索条件的当前目录 |
FileInfo[] GetFiles() | 返回当前目录的文件列表 |
FileInfo[] GetFiles(string searchPattern) | 返回当前目录中与给定的搜索模式匹配的文件列表 |
IEnumerable EnumerateDirectories() | 返回当前目录中目录信息的可枚举集合 |
FileSystemInfo[] GetFileSystemInfos() | 返回所有文件和目录的子目录中的项 |
使用举例:
private void test()
{
string path = @"d:\Log";
DirectoryInfo dir = new DirectoryInfo(path);
DirectoryInfo[] child_dirs = dir.GetDirectories();
string picpath = path + @"\PIC";
foreach (DirectoryInfo di in child_dirs)
{
string di_path = di.FullName.ToString();
if (di_path== picpath)
{
foreach (FileInfo pic in di.GetFiles())
{
TimeSpan t = DateTime.Now - pic.LastWriteTime;
if (t.Days >7)
{
pic.Delete();
}
}
}
}
}
3. 代码示例
3.1 删除文件和文件夹
static void Main(string[] args)
{
string path1 = Environment.CurrentDirectory + "\\MyTest";
string path2 = Environment.CurrentDirectory + "\\新建文本文档.txt";
//删除文件夹
if (Directory.Exists(path1))
Directory.Delete(path1, true);
//删除文件
if (File.Exists(path2))
File.Delete(path2);
Console.ReadKey();
}
3.2 文件流操作
3.2.1 利用流读取文件
//ReadAllLines
Console.WriteLine("--{0}", "ReadAllLines");
List<string> list = new List<string>(File.ReadAllLines(filePath));
list.ForEach(str =>
{
Console.WriteLine(str);
});
//ReadAllText
Console.WriteLine("--{0}", "ReadAllLines");
string fileContent = File.ReadAllText(filePath);
Console.WriteLine(fileContent);
//StreamReader
Console.WriteLine("--{0}", "StreamReader");
using (StreamReader sr = new StreamReader(filePath))
{
//方法一:从流的当前位置到末尾读取流
fileContent = string.Empty;
fileContent = sr.ReadToEnd();
Console.WriteLine(fileContent);
//方法二:一行行读取直至为NULL
fileContent = string.Empty;
string strLine = string.Empty;
while (strLine != null)
{
strLine = sr.ReadLine();
fileContent += strLine+"\r\n";
}
Console.WriteLine(fileContent);
}
3.3.2 写入文件和文件流
//WriteAllLines
File.WriteAllLines(filePath,new string[]{"11111","22222","3333"});
File.Delete(filePath);
//WriteAllText
File.WriteAllText(filePath, "11111\r\n22222\r\n3333\r\n");
File.Delete(filePath);
//StreamWriter
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.Write("11111\r\n22222\r\n3333\r\n");
sw.Flush();
}
3.3.3 关闭文件流
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
//将byte数组写入文件中
fs.Write(b, 0, b.Length);
//所有流类型都要关闭流,否则会出现内存泄露问题
fs.Close();
}
3.3 文件路径操作
(文件和文件夹的路径操作都在Path类中。另外还可以用Environment类,里面包含环境和程序的信息):
string dirPath = @"D:\TestDir";
string filePath = @"D:\TestDir\TestFile.txt";
Console.WriteLine("<<<<<<<<<<<{0}>>>>>>>>>>", "文件路径");
//获得当前路径
Console.WriteLine(Environment.CurrentDirectory);
//文件或文件夹所在目录
Console.WriteLine(Path.GetDirectoryName(filePath)); //D:\TestDir
Console.WriteLine(Path.GetDirectoryName(dirPath)); //D:\
//文件扩展名
Console.WriteLine(Path.GetExtension(filePath)); //.txt
//文件名
Console.WriteLine(Path.GetFileName(filePath)); //TestFile.txt
Console.WriteLine(Path.GetFileName(dirPath)); //TestDir
Console.WriteLine(Path.GetFileNameWithoutExtension(filePath)); //TestFile
//绝对路径
Console.WriteLine(Path.GetFullPath(filePath)); //D:\TestDir\TestFile.txt
Console.WriteLine(Path.GetFullPath(dirPath)); //D:\TestDir
//更改扩展名
Console.WriteLine(Path.ChangeExtension(filePath, ".jpg"));//D:\TestDir\TestFile.jpg
//根目录
Console.WriteLine(Path.GetPathRoot(dirPath)); //D:\
//生成路径
Console.WriteLine(Path.Combine(new string[] { @"D:\", "BaseDir", "SubDir", "TestFile.txt" })); //D:\BaseDir\SubDir\TestFile.txt
//生成随即文件夹名或文件名
Console.WriteLine(Path.GetRandomFileName());
//创建磁盘上唯一命名的零字节的临时文件并返回该文件的完整路径
Console.WriteLine(Path.GetTempFileName());
//返回当前系统的临时文件夹的路径
Console.WriteLine(Path.GetTempPath());
//文件名中无效字符
Console.WriteLine(Path.GetInvalidFileNameChars());
//路径中无效字符
Console.WriteLine(Path.GetInvalidPathChars());
3.4 文件属性操作
//use File class
Console.WriteLine(File.GetAttributes(filePath));
File.SetAttributes(filePath,FileAttributes.Hidden | FileAttributes.ReadOnly);
Console.WriteLine(File.GetAttributes(filePath));
//user FilInfo class
FileInfo fi = new FileInfo(filePath);
Console.WriteLine(fi.Attributes.ToString());
fi.Attributes = FileAttributes.Hidden | FileAttributes.ReadOnly; //隐藏与只读
Console.WriteLine(fi.Attributes.ToString());
//只读与系统属性,删除时会提示拒绝访问
fi.Attributes = FileAttributes.Archive;
Console.WriteLine(fi.Attributes.ToString());
3.5 文件夹操作
3.5.1 移动文件夹中的所有文件夹与文件到另一个文件夹
/// <summary>
/// 移动文件夹中的所有文件夹与文件到另一个文件夹
/// </summary>
/// <param name="sourcePath">源文件夹</param>
/// <param name="destPath">目标文件夹</param>
public static void MoveFolder(string sourcePath,string destPath)
{
if (Directory.Exists(sourcePath))
{
if (!Directory.Exists(destPath))
{
//目标目录不存在则创建
try
{
Directory.CreateDirectory(destPath);
}
catch (Exception ex)
{
throw new Exception("创建目标目录失败:" + ex.Message);
}
}
//获得源文件下所有文件
List<string> files = new List<string>(Directory.GetFiles(sourcePath));
files.ForEach(c =>
{
string destFile = Path.Combine(new string[]{destPath,Path.GetFileName(c)});
//覆盖模式
if (File.Exists(destFile))
{
File.Delete(destFile);
}
File.Move(c, destFile);
});
//获得源文件下所有目录文件
List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));
folders.ForEach(c =>
{
string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
//Directory.Move必须要在同一个根目录下移动才有效,不能在不同卷中移动。
//Directory.Move(c, destDir);
//采用递归的方法实现
MoveFolder(c, destDir);
});
}
else
{
throw new DirectoryNotFoundException("源目录不存在!");
}
}
3.5.2 复制文件夹中的所有文件夹与文件到另一个文件夹
/// <summary>
/// 复制文件夹中的所有文件夹与文件到另一个文件夹
/// </summary>
/// <param name="sourcePath">源文件夹</param>
/// <param name="destPath">目标文件夹</param>
public static void CopyFolder(string sourcePath,string destPath)
{
if (Directory.Exists(sourcePath))
{
if (!Directory.Exists(destPath))
{
//目标目录不存在则创建
try
{
Directory.CreateDirectory(destPath);
}
catch (Exception ex)
{
throw new Exception("创建目标目录失败:" + ex.Message);
}
}
//获得源文件下所有文件
List<string> files = new List<string>(Directory.GetFiles(sourcePath));
files.ForEach(c =>
{
string destFile = Path.Combine(new string[]{destPath,Path.GetFileName(c)});
File.Copy(c, destFile,true);//覆盖模式
});
//获得源文件下所有目录文件
List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));
folders.ForEach(c =>
{
string destDir = Path.Combine(new string[] { destPath, Path.GetFileName(c) });
//采用递归的方法实现
CopyFolder(c, destDir);
});
}
else
{
throw new DirectoryNotFoundException("源目录不存在!");
}
}