c# 高效读写文件

时间:2022-09-04 19:41:07
一、同步读写文件(在并发情况下不会发生文件被占用异常)

static void Main(string[] args)
{
Parallel.For(0, 10000, e =>
{

string str = "测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试\r\n";
                using (FileStream fs = new FileStream("d:\\a.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 1024, false))
                {
                    byte[] bty = Encoding.UTF8.GetBytes(str);
                    fs.Write(bty, 0, bty.Length);
                    fs.Close();
                }
    });
} 二、异步读写文件(在并发情况下不会发生文件被占用异常)

static void Main(string[] args)
{
Parallel.For(0, 10000, e =>
{
string str = "测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试\r\n";
FileStream fs = new FileStream("d:\\a.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 1024, false);

 
 

byte[] bty = Encoding.UTF8.GetBytes(str);
fs.BeginWrite(bty, 0, bty.Length, new AsyncCallback(EndWriteCallback), fs);

 
 

});
Console.WriteLine("执行完成");
Console.ReadKey();
}

private static void EndWriteCallback(IAsyncResult asr)
        {
            using (Stream str = (Stream)asr.AsyncState)
            {
                str.EndWrite(asr);
                Console.WriteLine("异步写入结束");
            }
        }