如何获取附加文件的实际附件大小或总大小

本文关键字:文件 何获取 获取 | 更新日期: 2023-09-27 18:02:58

嗨,我有一个数据表,它保存文件名与路径如下

String[] sizeArry = new String[] { "Byes", "KB", "MB" };
    String GetSize(ulong sizebytes, int index)
    {
        if (sizebytes < 1000) return sizebytes + sizeArry[index];
        else return GetSize(sizebytes / 1024, ++index);
    }
protected DataTable GetAttachment()
    {
        DataTable attachment = new DataTable();
        attachment.Columns.Add("ID", typeof(int));
        attachment.Columns.Add("Attachment", typeof(string));
        attachment.Columns.Add("Size", typeof(string));
        attachment.Rows.Add(1, " files/abc.txt");
        attachment.Rows.Add(2, "files/test.pdf");
        foreach (DataRow row in attachment.Rows)
        {
            string sFilename = row["Attachment"].ToString();
            string path = Server.MapPath(sFilename);
            FileInfo fi = new FileInfo(path);
            row["Attachment"] = fi.Name;
            row["Size"] = GetSize((ulong)fi.Length, 0);
        }
        Total(attachment);
        return attachment;
    }

它给我的结果如下abc.txt 3KB test.pdf 11MB现在我需要总结这些尺寸,需要在label中显示尺寸,所以有人能帮助我吗?我尝试了以下方法,但没有按要求工作

protected void Total(DataTable dt)
    {
        int size = 0;
        int cnt = 0;
        foreach (DataRow row in dt.Rows)
        {
            cnt++;
            string s = row["Size"].ToString().Remove(row["Size"].ToString().Length - 2);
            size = size + Convert.ToInt16(s);
        }
       label.Text = cnt.ToString() + " attachments " + size.ToString();
    }

如何获取附加文件的实际附件大小或总大小

首先要检查是否为Bytes, KiloBytes, MegaBytes

如果你知道它是什么,你可以调用你的助手方法,从字节->千字节->兆字节,像这样:

public static class Converter
{
    public static double ConvertBytesToMegabytes(long bytes)
    {
        return (bytes / 1024f) / 1024f;
    }
    public static double ConvertKilobytesToMegabytes(long kilobytes)
    {
        return kilobytes / 1024f;
    }  
}
编辑:

不需要计算行数,这里有一个属性:

label = dt.Rows.Count +" attachments " + size.ToString();

Edit2:

像这样可以工作。

protected void Total(DataTable dt)
{
    string label;
    double size = 0;
    foreach (DataRow row in dt.Rows)
    {
        var result = Regex.Match(row["Size"].ToString(),@"([0-9]+)(.*)");
        var fileSize = Convert.ToInt32(result.Groups[0].Value);
        var type = result.Groups[1].Value;
        switch (type)
        {
            case "B":
                size += ConvertBytesToMegabytes(fileSize);
                break;
            case "KB":
                size += ConvertKilobytesToMegabytes(fileSize);
                break;
            case "MB":
                size += fileSize;
                break;
            //ETC...
            default:
                break;
        }
    }
    label = dt.Rows.Count +" attachments " + size.ToString();       
}