参考代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace FileDemo
{
class Program
{
static void Main(string[] args)
{
//1.
FileStream f=File.Open("cs.bin",FileMode.Create); //如果文件存在,则覆盖原来的文件
byte[] info = new UTF8Encoding(true).GetBytes("a1汉");
// Add some information to the file.
f.Write(info, 0, info.Length);
byte[] inf2 = new byte[]{0x32,0x11 };
f.Write(inf2, 0, 2);
f.WriteByte(0xee);
f.Close();
string s=File.ReadAllText(@"cs.bin", Encoding.UTF8);
byte[] b = File.ReadAllBytes(@"cs.bin");
Console.WriteLine(s);
//2.
//写入文件
string path = @"cs2.txt"; // 文件路径
using (StreamWriter writer = new StreamWriter(path))
{
string content = "Hello, World!"; // 要写入文件的内容
writer.WriteLine(content); // 写入一行内容到文件
for(int i=0;i<10;i++)
{
writer.WriteLine((i+1).ToString()); // 写入一行内容到文件
}
}
//读取文件
using (StreamReader reader = new StreamReader(path))//使用using语句来确保资源被正确释放,以避免资源泄漏
{
string line;
while ((line = reader.ReadLine()) != null) // 逐行读取文件内容,每次读取一行,读取到末尾的时候为空
{
Console.WriteLine(line); // 输出每行内容到控制台
}
}
//3.
string stuInfoFile = @"stuInfo.txt"; // 文件路径
List<float> stuInfoList = new List<float>();
//读取文件
using (StreamReader reader = new StreamReader(stuInfoFile,Encoding.UTF8))//使用using语句来确保资源被正确释放,以避免资源泄漏
{
string line;
int i = 0;
while ((line = reader.ReadLine()) != null) // 逐行读取文件内容,每次读取一行,读取到末尾的时候为空
{
stuInfoList.Add(float.Parse(line.Split(',')[1]));
i++;
if (i >= 3)
break;
}
}
float avg = stuInfoList.ToArray().Average();
using (StreamWriter writer = new StreamWriter(stuInfoFile,true,Encoding.UTF8))
{
writer.WriteLine("\n"+avg.ToString()); // 写入一行内容到文件
}
}
}
}
StuInfo.txt 内容:
张三,100
李四, 40
王麻子,78
---------------
72.66666