文件异步读写

 1.ReadAllLines和AppendAllLines

//获取文件夹路径    当前文件夹下dataFile文件夹
string FolderPath = Directory.GetCurrentDirectory() + @"\dataFile";

//判断指定路径文件夹是否存在
if (Directory.Exists(FolderPath))
{
    //Directory.GetFiles(Path).Length > 0  获取指定路径文件夹下的文件数量

    //判断指定路径下文件是否存在
    if (File.Exists(FolderPath + @"\widthData.txt"))
    {
        //读取数据
        string[] strlist = File.ReadAllLines(FolderPath + @"\widthData.txt");

        //数据展示  声明Label控件添加至界面,用于显示内容
        for (int i = 0; i < strlist.Length; i++)
        {
            Label label = new Label();
            label.Text = strlist[i];
            label.Width = panel2.Width;
            label.Font = new Font("楷体", 12);
            label.Location = new Point(0, 30 * pane2Number);
            pane2Number++;
            
            //向WinForm的panel面板控件中添加label控件
            //Invoke() 会阻塞调用线程,直到 UI 线程处理完委托为止。(同步更新)
            //BeginInvoke() 不会阻塞调用线程,而是在 UI 线程上异步执行委托。(异步更新)
            panel2.BeginInvoke(new Action(() =>
            {
                panel2.Controls.Add(label);
            }));
        }
    }
    else
    {
        //如果文件不存在,新建文件
        File.Create(FolderPath + @"\widthData.txt");
    }
}
else
{
    //如果文件夹不存在,新建文件夹,并新建文件
    Directory.CreateDirectory(FolderPath);
    File.Create(FolderPath + @"\widthData.txt");
}



//向指定文件写入一行内容    AppendAllLines参数是数组
string[] strlist = new string[1] { str };
File.AppendAllLines(FolderPath + @"\widthData.txt", strlist);




2.FileStream类进行读取、写入

//在使用 FileStream 时,需要注意及时关闭以释放资源

string FilePath = Directory.GetCurrentDirectory() + @"\dataFile\widthData.txt";


//1.通常使用using语句来自动处理关闭操作
using (FileStream fileStream = File.OpenRead(FilePath))
{
    //判断指定路径文件是否存在
    if (fileStream != null){ 
        ...........
    }
}


//2.手动关闭 fileStream.Close();
FileStream fileStream = File.OpenRead(FilePath);
if (fileStream != null)
{
    ..........
}
fileStream.Close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值