Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# RAZOR-在网页上显示文件大小_C#_File_Asp.net Mvc 3_Razor - Fatal编程技术网

C# RAZOR-在网页上显示文件大小

C# RAZOR-在网页上显示文件大小,c#,file,asp.net-mvc-3,razor,C#,File,Asp.net Mvc 3,Razor,我已经研究了一段时间了,仍然没有找到正确的答案。我需要在我的.cshtml文件中的文件名旁边显示文件大小。我需要使用Razor来实现这一点……除非有人有一个像.GetExtension(file)或.GetFileNameWithoutExtension(file)这样的文件方法 以下是我不断遇到的问题: 左图显示了我想要显示的内容。。。磁盘上的实际文件大小。正确的图片显示在网页上,我甚至不确定它显示的是什么,但我只是像在其他帖子中建议的那样,在foreach循环中使用@file.Length

我已经研究了一段时间了,仍然没有找到正确的答案。我需要在我的
.cshtml
文件中的文件名旁边显示文件大小。我需要使用Razor来实现这一点……除非有人有一个像
.GetExtension(file)
.GetFileNameWithoutExtension(file)
这样的文件方法

以下是我不断遇到的问题:

左图显示了我想要显示的内容。。。磁盘上的实际文件大小。正确的图片显示在网页上,我甚至不确定它显示的是什么,但我只是像在其他帖子中建议的那样,在foreach循环中使用
@file.Length
,如下所示

<table class="table table-responsive table-hover table-bordered table-condensed margin-bottom-none">
    <!--############ HEADER SECTION ############-->
    <tr class="bg-blue topRow-no-hover">
        <td class="width-70">
            <b>FORM NAME</b>
        </td>
        <td class="width-15">
            <b>FILE TYPE</b>
        </td>
        <td class="width-15">
            <b>PUBLISHED</b>
        </td>
    </tr>
    <!--############ BODY OF TABLE ############-->
    @foreach(var file in Directory.GetFiles(serverPath)){
        <tr class="pointer">
            <td>
                @Path.GetFileNameWithoutExtension(file)
                <a href="@Href(@path, Path.GetFileName(file))" target="_blank"></a>
            </td>
            <td>
                @getFileType(Path.GetExtension(file))
            </td>
            <td>
                @file.Length
            </td>
        </tr>
    }
</table>
但是,由于所有文件的大小都不超过1024,因此它们都会追加KB,如下图所示


如果有人对这里发生的事情有任何线索,以及我如何纠正它,请帮忙。提前感谢。

您需要使用DirectoryInfo并处理DirectoryInfo.EnumerateFiles返回的FileInfo对象。在这里,每个FileInfo对象都有表示文件大小的Length属性。如果您愿意,我将查看您的建议并给出结果。
@getFileSize(file.Length)
public string getFileSize(long source){
    const int byteConversion = 1024;
    double bytes = Convert.ToDouble(source);

    if (bytes >= Math.Pow(byteConversion, 3)) //GB Range
    {
        return string.Concat(Math.Round(bytes / Math.Pow(byteConversion, 3), 2), " GB");
    }
    else if (bytes >= Math.Pow(byteConversion, 2)) //MB Range
    {
        return string.Concat(Math.Round(bytes / Math.Pow(byteConversion, 2), 2), " MB");
    }
    else if (bytes >= byteConversion) //KB Range
    {
        return string.Concat(Math.Round(bytes / byteConversion, 2), " KB");
    }
    else //Bytes
    {
        return string.Concat(bytes, " Bytes");
    }
}