
在C#中,文件操作主要包括读写、创建、删除等。以下是几个C#文件操作的基本示例:
- 创建并写入文本文件:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = @"C:\Temp\MyFile.txt";
// 创建或打开文件以追加模式(如果文件已存在则不会覆盖)
using (StreamWriter sw = new StreamWriter(filePath, true))
{
sw.WriteLine("Hello, World!");
sw.WriteLine("This is a test line.");
}
}
}
- 读取文本文件内容:
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = @"C:\Temp\MyFile.txt";
// 打开文件进行读取
using (StreamReader sr = new StreamReader(filePath))
{
string line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
}
- 复制文件:
using System;
using System.IO;
class Program
{
static void Main()
{
string sourcePath = @"C:\Temp\OriginalFile.txt";
string destinationPath = @"C:\Temp\CopiedFile.txt";
// 复制文件
File.Copy(sourcePath, destinationPath, true); // 第三个参数为true表示如果目标文件已存在则覆盖它
}
}
4. **删除文件:**
```csharp
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = @"C:\Temp\ToDelete.txt";
// 检查文件是否存在,如果存在则删除
if (File.Exists(filePath))
{
File.Delete(filePath);
Console.WriteLine($"File {filePath} has been deleted.");
}
else
{
Console.WriteLine($"File {filePath} does not exist.");
}
}
}
- 创建目录及文件:
using System;
using System.IO;
class Program
{
static void Main()
{
string directoryPath = @"C:\Temp\NewDirectory";
string filePath = Path.Combine(directoryPath, "NewFile.txt");
// 创建目录(如果不存在)
Directory.CreateDirectory(directoryPath);
// 创建并写入文件
using (StreamWriter sw = new StreamWriter(filePath))
{
sw.WriteLine("Content of the new file.");
}
Console.WriteLine($"Directory {directoryPath} and file {filePath} have been created.");
}
}
以上代码片段展示了如何使用C#进行基本的文件和目录操作,包括创建、写入、读取、复制和删除文件以及创建目录。记得处理可能发生的异常,如权限不足、路径无效等。
本文介绍了如何在C#中进行基本的文件操作,包括创建文本文件并写入内容,读取文件,复制文件,删除文件,以及创建目录。示例代码涵盖了这些操作,并强调了异常处理的重要性。
5239

被折叠的 条评论
为什么被折叠?



