如何获取文件的大小?c#获取文件大小的示例代码

济南云服务器 2025年6月13日08:30:40C#教程如何获取文件的大小?c#获取文件大小的示例代码已关闭评论13阅读模式

开发软件时,会经常遇到各种操作文件的工作,今天,济南网站建设小编就为大家分享一个小案例,如何通过c#编程语言获取某个文件的大小?有需要的朋友可以过来参考一下。

关键代码:

 

  1. class Program
  2. {
  3. static void Main()
  4. {
  5. string filePath = @"C:\path\to\your\file.txt";
  6.  
  7. if (File.Exists(filePath))
  8. {
  9. FileInfo fileInfo = new FileInfo(filePath);
  10. long fileSize = fileInfo.Length; // 获取文件大小(单位:字节)
  11.  
  12. Console.WriteLine($"文件大小为:{fileSize} 字节");
  13. // 可选:显示为 KB、MB 等
  14. Console.WriteLine($"大约 {Math.Round((double)fileSize / 1024, 2)} KB");
  15. Console.WriteLine($"大约 {Math.Round((double)fileSize / (1024 * 1024), 2)} MB");
  16. }
  17. else
  18. {
  19. Console.WriteLine("文件不存在!");
  20. }
  21. }
  22. }

济南云服务器
  • 本文由 发表于 2025年6月13日08:30:40
  • 转载请务必保留本文链接:http://news.hcsw666.com/2098