在C#.NET中,文件处理是一个重要的功能。以下是一些常见的文件处理任务和相应的代码示例:
using System.IO;
string filePath = "path/to/file.txt";
using (StreamReader sr = new StreamReader(filePath))
{
string line = sr.ReadLine();
while (line != null)
{
Console.WriteLine(line);
line = sr.ReadLine();
}
}
using System.IO;
string filePath = "path/to/file.txt";
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.WriteLine("Hello, World!");
}
using System.IO;
string sourceFilePath = "path/to/source/file.txt";
string destinationFilePath = "path/to/destination/file.txt";
File.Copy(sourceFilePath, destinationFilePath, true);
using System.IO;
string filePath = "path/to/file.txt";
File.Delete(filePath);
using System.IO;
string sourceFilePath = "path/to/source/file.txt";
string destinationFilePath = "path/to/destination/file.txt";
File.Move(sourceFilePath, destinationFilePath);
using System.IO;
string filePath = "path/to/file.txt";
bool fileExists = File.Exists(filePath);
using System.IO;
string filePath = "path/to/file.txt";
FileInfo fileInfo = new FileInfo(filePath);
Console.WriteLine("File Name: " + fileInfo.Name);
Console.WriteLine("File Size: " + fileInfo.Length + " bytes");
Console.WriteLine("File Creation Time: " + fileInfo.CreationTime);
Console.WriteLine("File Last Access Time: " + fileInfo.LastAccessTime);
Console.WriteLine("File Last Write Time: " + fileInfo.LastWriteTime);
using System.IO;
string folderPath = "path/to/folder";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
Directory.Delete(folderPath, true);
using System.IO;
string folderPath = "path/to/folder";
foreach (string file in Directory.GetFiles(folderPath))
{
Console.WriteLine("File: " + file);
}
foreach (string directory in Directory.GetDirectories(folderPath))
{
Console.WriteLine("Directory: " + directory);
}
以上是一些常见的文件处理任务和相应的代码示例。在C#.NET中,可以使用System.IO
命名空间中的类和方法来完成各种文件处理任务。
领取专属 10元无门槛券
手把手带您无忧上云