C# 获取, 读取指定文件大小, 返回单位为字节
using System;
using System.IO;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
long length = FileSize("D:\\001.txt");
Console.WriteLine(length);
Console.Read();
}
/// <summary>
/// 获取, 读取指定文件大小, 返回单位为字节
/// </summary>
/// <param name="path">文件路径</param>
/// <returns></returns>
public static long FileSize(string path)
{
// 空路径名是不合法的
if (string.IsNullOrEmpty(path))
{
throw new ArgumentException("Empty path name is not legal.", "path");
}
// 判断路径是否存在
if (!File.Exists(path))
{
throw new FileNotFoundException("Could not find file '" + path + "'.", path);
}
using (System.IO.FileStream fileStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
return fileStream.Length;
}
}
}
}