用C#写txt文件管理系统的代码
时间: 2023-06-15 13:05:40 浏览: 63
以下是一个简单的用C#编写的txt文件管理系统的代码示例:
```csharp
using System;
using System.IO;
namespace FileManagementSystem
{
class Program
{
static void Main(string[] args)
{
string directoryPath = @"C:\Users\User\Desktop\Files"; // 设置文件夹路径
string filePath = directoryPath + @"\test.txt"; // 设置文件路径
string content = "Hello, world!"; // 设置文件内容
if (!Directory.Exists(directoryPath)) // 如果文件夹不存在,创建文件夹
{
Directory.CreateDirectory(directoryPath);
Console.WriteLine("Directory created: " + directoryPath);
}
if (!File.Exists(filePath)) // 如果文件不存在,创建文件
{
File.Create(filePath).Dispose();
Console.WriteLine("File created: " + filePath);
}
using (StreamWriter writer = new StreamWriter(filePath)) // 写入文件内容
{
writer.WriteLine(content);
Console.WriteLine("Content written to file: " + content);
}
using (StreamReader reader = new StreamReader(filePath)) // 读取文件内容
{
string line = reader.ReadLine();
Console.WriteLine("Content read from file: " + line);
}
Console.ReadLine();
}
}
}
```
该程序首先检查指定的文件夹是否存在,如果不存在则创建一个。然后检查指定的文件是否存在,如果不存在则创建一个。然后向文件写入内容并读取文件内容。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)