首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

c#.net中的文件处理

在C#.NET中,文件处理是一个重要的功能。以下是一些常见的文件处理任务和相应的代码示例:

  1. 读取文件
代码语言:csharp
复制
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();
    }
}
  1. 写入文件
代码语言:csharp
复制
using System.IO;

string filePath = "path/to/file.txt";
using (StreamWriter sw = new StreamWriter(filePath))
{
    sw.WriteLine("Hello, World!");
}
  1. 文件复制
代码语言:csharp
复制
using System.IO;

string sourceFilePath = "path/to/source/file.txt";
string destinationFilePath = "path/to/destination/file.txt";
File.Copy(sourceFilePath, destinationFilePath, true);
  1. 文件删除
代码语言:csharp
复制
using System.IO;

string filePath = "path/to/file.txt";
File.Delete(filePath);
  1. 文件移动
代码语言:csharp
复制
using System.IO;

string sourceFilePath = "path/to/source/file.txt";
string destinationFilePath = "path/to/destination/file.txt";
File.Move(sourceFilePath, destinationFilePath);
  1. 文件检查
代码语言:csharp
复制
using System.IO;

string filePath = "path/to/file.txt";
bool fileExists = File.Exists(filePath);
  1. 获取文件信息
代码语言:csharp
复制
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);
  1. 文件夹操作
代码语言:csharp
复制
using System.IO;

string folderPath = "path/to/folder";
if (!Directory.Exists(folderPath))
{
    Directory.CreateDirectory(folderPath);
}
Directory.Delete(folderPath, true);
  1. 遍历文件夹和文件
代码语言:csharp
复制
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命名空间中的类和方法来完成各种文件处理任务。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券