C#中的FileInfo和File类都提供了许多方法和属性来操作文件,但它们的使用方法有所不同。下面是FileInfo和File类常用的方法举例说明:
FileInfo fileInfo = new FileInfo("C:\\test.txt");
using (StreamWriter writer = fileInfo.CreateText())
{
writer.WriteLine("Hello, FileInfo!");
}
FileInfo fileInfo = new FileInfo("C:\\test.txt");
fileInfo.Delete();
FileInfo fileInfo = new FileInfo("C:\\test.txt");
fileInfo.MoveTo("D:\\test.txt");
FileInfo fileInfo = new FileInfo("C:\\test.txt");
fileInfo.CopyTo("D:\\test.txt");
FileInfo fileInfo = new FileInfo("C:\\test.txt");
if (fileInfo.Exists)
{
// 文件存在
}
FileInfo fileInfo = new FileInfo("C:\\test.txt");
long length = fileInfo.Length;
FileInfo fileInfo = new FileInfo("C:\\test.txt");
string name = fileInfo.Name;
string content = File.ReadAllText("C:\\test.txt");
File.WriteAllText("C:\\test.txt", "Hello, File!");
File.Delete("C:\\test.txt");
File.Move("C:\\test.txt", "D:\\test.txt");
File.Copy("C:\\test.txt", "D:\\test.txt");
if (File.Exists("C:\\test.txt"))
{
// 文件存在
}
DateTime creationTime = File.GetCreationTime("C:\\test.txt");
FileInfo类更适合用于操作单个文件的信息和属性,例如文件名、大小、创建时间和最后访问时间等。
File类更适合用于文件的读取、写入和复制等操作,例如读取文件内容、写入字符串到文件、复制或移动文件等。