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

时间:2014-05-13 09:35:23

标签: c# asp.net

大家好我有一个DataTable,其中包含带路径的文件名,如下所示

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();
    }

1 个答案:

答案 0 :(得分:2)

首先,您必须检查它是BytesKiloBytesMegaBytes等。

如果您知道它是什么,您可以调用您的帮助方法,从Bytes-&gt; KiloBytes-&gt; 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();       
}