一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

asp.net c# 获得文件大小各种方法总结

时间:2022-06-25 08:19:52 编辑:袖梨 来源:一聚教程网

文件信息类的一个Extension Method,返回文件大小的格式化的版本。比如:1 GB or 100 B and it at max it will have two decimals.添加下面代码到同样的命名空间的公共静态类,创建新的FileInfo,调用GetFileSize。

C# 获取文件大小,创建时间,文件信息,FileInfo类的属性表 OpenFileDialog openFileDialog1 = new OpenFileDialog();

 

 代码如下 复制代码

  if(openFileDialog1.ShowDialog() == DialogResult.OK)
   {
    openFileDialog1.FileName;
    System.IO.FileInfo file = new System.IO.FileInfo(openFileDialog1.FileName);

                file.Name;//文件名
                file.Length.ToString();//大小",
                file.LastAccessTime.ToString();//最后访问时间
                file.LastWriteTime.ToString();//最后修改时间
                file.DirectoryName;//路径
   }

获取大小并转换单位MB

 

 代码如下 复制代码
      ///
        /// Gets a files formatted size.
        ///

        /// The file to return size of.
        ///
        public static string GetFileSize(this FileInfo file)
        {
            try
            {
                //determine all file sizes
                double sizeinbytes = file.Length;
                double sizeinkbytes = Math.Round((sizeinbytes / 1024));
                double sizeinmbytes = Math.Round((sizeinkbytes / 1024));
                double sizeingbytes = Math.Round((sizeinmbytes / 1024));
                if (sizeingbytes > 1)
                    return string.Format("{0} GB", sizeingbytes); //returns size in gigabytes
                else if (sizeinmbytes > 1)
                    return string.Format("{0} MB", sizeinmbytes); //returns size in megabytes if less than one gigabyte
                else if (sizeinkbytes > 1)
                    return string.Format("{0} KB", sizeinkbytes); //returns size in kilabytes if less than one megabyte
                else
                    return string.Format("{0} B", sizeinbytes); //returns size in bytes if less than one kilabyte
            }
            catch { return "Error Getting Size"; } //catches any possible error and just returns error getting size
        }

获取文件夹及文件占用空间

首先通过windows API获取磁盘的相关信息。

 //调用windows API获取磁盘空闲空间
//导入库

 代码如下 复制代码

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
static extern bool GetDiskFreeSpace([MarshalAs(UnmanagedType.LPTStr)]string rootPathName,
ref int sectorsPerCluster, ref int bytesPerSector, ref int numberOfFreeClusters, ref int totalNumbeOfClusters);
  下面是具体代码。第一次写文章就简单点了。

    

 ///


/// 获取指定路径的大小
///

/// 路径
///
public static long GetDirectoryLength(string dirPath)
{
long len = 0;
//判断该路径是否存在(是否为文件夹)
if (!Directory.Exists(dirPath))
{
//查询文件的大小
len = FileSize(dirPath);
}
else
{
//定义一个DirectoryInfo对象
DirectoryInfo di = new DirectoryInfo(dirPath);
//通过GetFiles方法,获取di目录中的所有文件的大小
foreach (FileInfo fi in di.GetFiles())
{
len += fi.Length;
}
//获取di中所有的文件夹,并存到一个新的对象数组中,以进行递归
DirectoryInfo[] dis = di.GetDirectories();
if (dis.Length > 0)
{
for (int i = 0; i < dis.Length; i++)
{
len += GetDirectoryLength(dis[i].FullName);
}
}
}
return len;
}
///
/// 获取指定路径的占用空间
///

/// 路径
///
public static long GetDirectorySpace(string dirPath)
{
//返回值
long len = 0;
//判断该路径是否存在(是否为文件夹)
if (!Directory.Exists(dirPath))
{
//如果是文件,则调用
len = FileSpace(dirPath);
}
else
{
//定义一个DirectoryInfo对象
DirectoryInfo di = new DirectoryInfo(dirPath);
//本机的簇值
long clusterSize = GetClusterSize(di);
//遍历目录下的文件,获取总占用空间
foreach (FileInfo fi in di.GetFiles())
{
//文件大小除以簇,余若不为0
if (fi.Length % clusterSize != 0)
{
decimal res = fi.Length / clusterSize;
//文件大小除以簇,取整数加1。为该文件占用簇的值
int clu = Convert.ToInt32(Math.Ceiling(res)) + 1;
long result = clusterSize * clu;
len += result;
}
else
{
//余若为0,则占用空间等于文件大小
len += fi.Length;
}
}
//获取di中所有的文件夹,并存到一个新的对象数组中,以进行递归
DirectoryInfo[] dis = di.GetDirectories();
if (dis.Length > 0)
{
for (int i = 0; i < dis.Length; i++)
{
len += GetDirectorySpace(dis[i].FullName);
}
}
}
return len;
}
//所给路径中所对应的文件大小
public static long FileSize(string filePath)
{
//定义一个FileInfo对象,是指与filePath所指向的文件相关联,以获取其大小
FileInfo fileInfo = new FileInfo(filePath);
return fileInfo.Length;
}
//所给路径中所对应的文件占用空间
public static long FileSpace(string filePath)
{
long temp = 0;
//定义一个FileInfo对象,是指与filePath所指向的文件相关联,以获取其大小
FileInfo fileInfo = new FileInfo(filePath);
long clusterSize = GetClusterSize(fileInfo);
if (fileInfo.Length % clusterSize != 0)
{
decimal res = fileInfo.Length / clusterSize;
int clu = Convert.ToInt32(Math.Ceiling(res)) + 1;
temp = clusterSize * clu;
}
else
{
return fileInfo.Length;
}
return temp;
}
public static DiskInfo GetDiskInfo(string rootPathName)
{
DiskInfo diskInfo = new DiskInfo();
int sectorsPerCluster = 0, bytesPerSector = 0, numberOfFreeClusters = 0, totalNumberOfClusters = 0;
GetDiskFreeSpace(rootPathName, ref sectorsPerCluster, ref bytesPerSector, ref numberOfFreeClusters, ref totalNumberOfClusters);
//每簇的扇区数
diskInfo.SectorsPerCluster = sectorsPerCluster;
//每扇区字节
diskInfo.BytesPerSector = bytesPerSector;
return diskInfo;
}
////
/// 结构。硬盘信息
///

public struct DiskInfo
{
public string RootPathName;
//每簇的扇区数
public int SectorsPerCluster;
//每扇区字节
public int BytesPerSector;
public int NumberOfFreeClusters;
public int TotalNumberOfClusters;
} ///
/// 获取每簇的字节
///

/// 指定文件
///
public static long GetClusterSize(FileInfo file)
{
long clusterSize = 0;
DiskInfo diskInfo = new DiskInfo();
diskInfo = GetDiskInfo(file.Directory.Root.FullName);
clusterSize = (diskInfo.BytesPerSector * diskInfo.SectorsPerCluster);
return clusterSize;
}
///
/// 获取每簇的字节
///

/// 指定目录
///
public static long GetClusterSize(DirectoryInfo dir)
{
long clusterSize = 0;
DiskInfo diskInfo = new DiskInfo();
diskInfo = GetDiskInfo(dir.Root.FullName);
clusterSize = (diskInfo.BytesPerSector * diskInfo.SectorsPerCluster);
return clusterSize;
}

热门栏目