You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现WPF进度条流畅更新?获取文件真实大小的方法

解决方案

问题根源

你遇到的问题是因为FileInfo.Length会缓存文件的元数据(包括大小),系统不会自动实时更新这个缓存,只有主动触发刷新时,才能获取到文件的最新大小。

修复方法

方法1:调用FileInfo.Refresh()刷新缓存

在获取每个文件的Length前,调用Refresh()强制从磁盘读取最新的文件元数据:

public async void RenderStatus()
{
    string vidPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FCS", "VidBin");
    DirectoryInfo vidDir = new DirectoryInfo(vidPath);
    while (IsBusy)
    {
        long tempCompleteVideoSize = 0;
        foreach(var file in vidDir.GetFiles())
        {
            file.Refresh(); // 强制刷新文件元数据,获取最新大小
            tempCompleteVideoSize += file.Length;                    
        }
        await Application.Current.Dispatcher.BeginInvoke(new Action(() =>
        {
            CurrentCompleteVideoSize = tempCompleteVideoSize;
            NotifyPropertyChanged(nameof(CurrentCompleteVideoSize));
            ExportPercentProgress = Math.Round((Convert.ToDouble(CurrentCompleteVideoSize) / Convert.ToDouble(TotalCompleteVideoSize) * 100), 2);
            NotifyPropertyChanged(nameof(ExportPercentProgress));
        }), DispatcherPriority.Render);
        
        // 增加延迟,避免循环过于频繁占用CPU
        await Task.Delay(100);
    }
}

方法2:使用File.GetLength()直接获取实时大小

File.GetLength()每次都会直接从磁盘读取文件的最新大小,不依赖缓存,代码更简洁:

public async void RenderStatus()
{
    string vidPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "FCS", "VidBin");
    DirectoryInfo vidDir = new DirectoryInfo(vidPath);
    while (IsBusy)
    {
        long tempCompleteVideoSize = 0;
        foreach(var file in vidDir.GetFiles())
        {
            tempCompleteVideoSize += File.GetLength(file.FullName); // 直接读取实时文件大小
        }
        await Application.Current.Dispatcher.BeginInvoke(new Action(() =>
        {
            CurrentCompleteVideoSize = tempCompleteVideoSize;
            NotifyPropertyChanged(nameof(CurrentCompleteVideoSize));
            ExportPercentProgress = Math.Round((Convert.ToDouble(CurrentCompleteVideoSize) / Convert.ToDouble(TotalCompleteVideoSize) * 100), 2);
            NotifyPropertyChanged(nameof(ExportPercentProgress));
        }), DispatcherPriority.Render);
        
        await Task.Delay(100);
    }
}

额外优化建议

  • 控制轮询频率:添加await Task.Delay(100)(可根据需求调整间隔),防止循环持续占用CPU资源。
  • 优先主动更新:如果是你的程序正在生成这些视频文件,建议在写入文件的代码中直接累加已写入的大小,同步更新CurrentCompleteVideoSize。这种方式比轮询目录更高效准确,无需依赖磁盘读取。

内容的提问来源于stack exchange,提问作者Jacob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 02:42:26