c#在硬盘路径下进行文件操作
时间: 2024-05-16 22:14:28 浏览: 15
在 C# 中,可以使用 System.IO 命名空间中的类来进行硬盘路径下的文件操作。
以下是一些常用的文件操作方法:
1. 创建文件:
```csharp
string filePath = @"C:\Test\test.txt";
if (!File.Exists(filePath))
{
using (StreamWriter sw = File.CreateText(filePath))
{
sw.WriteLine("Hello, world!");
}
}
```
2. 读取文件:
```csharp
string filePath = @"C:\Test\test.txt";
if (File.Exists(filePath))
{
using (StreamReader sr = File.OpenText(filePath))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
```
3. 写入文件:
```csharp
string filePath = @"C:\Test\test.txt";
if (File.Exists(filePath))
{
using (StreamWriter sw = File.AppendText(filePath))
{
sw.WriteLine("This is a new line.");
}
}
```
4. 复制文件:
```csharp
string sourceFilePath = @"C:\Test\test.txt";
string destFilePath = @"C:\Test\test_copy.txt";
File.Copy(sourceFilePath, destFilePath);
```
5. 删除文件:
```csharp
string filePath = @"C:\Test\test.txt";
if (File.Exists(filePath))
{
File.Delete(filePath);
}
```
注意:在进行文件操作时,需要确保程序拥有足够的权限来访问指定的路径和文件。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)