1.File类:
提供用于创建、复制、删除、移动和打开文件的静态方法,并协助创建 FileStream 对象。
msdn:http://msdn.microsoft.com/zh-cn/library/system.io.file(v=VS.80).aspx
2.FileInfo类:
提供创建、复制、删除、移动和打开文件的实例方法,并且帮助创建 FileStream 对象
msdn:http://msdn.microsoft.com/zh-cn/library/system.io.fileinfo(v=VS.80).aspx
3.Directory类:
公开用于创建、移动和枚举通过目录和子目录的静态方法。
msdn:http://msdn.microsoft.com/zh-cn/library/system.io.directory.aspx
4.DirectoryInfo类:
公开用于创建、移动和枚举目录和子目录的实例方法。
msdn:http://msdn.microsoft.com/zh-cn/library/system.io.directoryinfo.aspx
判断文件夹是否存在:
System.IO.Directory.Exists(@"D:\TestDir");
创建文件夹 :
System.IO.Directory.CreateDirectory(@"D:\TestDir");
删除文件夹:
System.IO.Directory.Delete(@"D:\TestDir");
删除该目录以及其所有内容:
System.IO.Directory.Delete(@"D:\TestDir",true);
判断文件是否存在:
System.IO.File.Exists(@"D:\TestDir\TestFile.txt");
创建文件:
using (System.IO.File.Create(@"D:\TestDir\TestFile.txt"));
删除文件:
System.IO.File.Delete(@"D:\TestDir\TestFile.txt");
拷贝文件:
System.IO.File.Copy(string sourceFileName, string destFileName, bool overwrite);
C#流(stream):https://www.cnblogs.com/vaevvaev/p/7150519.html
其中类Stream为抽象类。由此有三个派生类:
MemoryStream:对内存进行读取与写入
BufferedStream:对缓冲器进行读取/写入
FileStream:对文件执行读取与写入
TextReader/Writer为抽象类。由此派生类:
StreamReader/StreamWirter
StringReader/StringWriter
读取文件:
一、直接使用File类
1.public static string ReadAllText(string path);
2.public static string[] ReadAllLines(string path);
3.public static IEnumerable<string> ReadLines(string path);
4.public static byte[] ReadAllBytes(string path);
以上获得内容是一样的,只是返回类型不同罢了,根据自己需要调用。
二、利用流读取文件
//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);
}
写入文件和文件流:
//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();
}
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
//将byte数组写入文件中
fs.Write(b, 0, b.Length);
//所有流类型都要关闭流,否则会出现内存泄露问题
fs.Close();
}
文件路径(文件和文件夹的路径操作都在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());
文件属性操作:
//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());
移动文件夹中的所有文件夹与文件到另一个文件夹:
/// <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("源目录不存在!");
}
}
复制文件夹中的所有文件夹与文件到另一个文件夹:
/// <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("源目录不存在!");
}
}