主要说明文件目录、流之间的关系。
在C#中,可以使用System.IO命名空间中的类来操作文件和目录。
流(Stream)是C#中处理文件的另一种方式,它代表了一个数据的序列,可以用来读取和写入文件。
使用文件和目录,以及使用流来读取和写入文件的示例
1、创建一个新文件并写入数据完整代码示例:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileUse
{
internal class Program
{
static void Main(string[] args)
{
string filePath = "test.txt";
// 创建一个新文件并写入数据
using (FileStream stream = File.Create(filePath))
{
byte[] data = new byte[] { 65, 66, 67, 68, 69 };
stream.Write(data, 0, data.Length);
}
}
}
}
上面的示例中,使用File.Create方法创建了一个名为“test.txt”的新文件,并获取了一个FileStream对象。然后,使用该对象的Write方法将数据写入文件。(..\FileUse\bin\Debug)默认这个目录下。
- 读取文件中的数据完整代码示例:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.Remoting.Lifetime;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;
namespace FileUseRead
{
internal class Program
{
static void Main(string[] args)
{
//读取文件中的数据
using (FileStream stream = File.OpenRead(@".\test.txt"))
{
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string data = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine(data);
}
}
}
}
前提:把文件“test.txt”在上一步创建文件的时候拷贝到当前执行的Debug目录下。不然会报错
上面的示例中,使用File.OpenRead方法打开了名为“test.txt”的文件,并获取了一个FileStream对象。然后,使用该对象的Read方法将数据读入缓冲区,再使用System.Text.Encoding.ASCII.GetString方法将缓冲区中的数据转换为字符串并输出。