c#异步操作文件
|
admin
2026年1月19日 20:8
本文热度 59
|
using static System.Net.Mime.MediaTypeNames;
namespace fileOperate{ internal class Program { static void Main(string[] args) { write(@"E:\test.txt", "hello world").Wait(); Thread.Sleep(1000); string str = read(@"E:\test.txt").Result; Console.WriteLine(str); }
public async static Task write(string filePath, string str) { if (!Directory.Exists(Path.GetDirectoryName(filePath))) Directory.CreateDirectory(Path.GetDirectoryName(filePath)); using (StreamWriter sw = new StreamWriter(filePath)) { await sw.WriteAsync(str); } }
public async static Task<string> read(string filePath) { if (File.Exists(filePath)) { using (StreamReader sr = new StreamReader(filePath)) { return await sr.ReadToEndAsync(); } } return ""; }
}}
该文章在 2026/1/20 10:30:54 编辑过