I am working with a Visual Studio model, and I have a page for "downloads" that displays file name, file size, and a link. However, I am trying to convert the file size to a readable format. I have found several methods for doing this, but I think where I am getting stuck is how to incorporate that into the code that I am already using. For instance, I already have a FileSize variable, so I want to incorporate that into the code for the conversion. Here is my existing code for the model itself:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Hosting;
namespace SupportToolkit.Models
{
public class DataClassesModel
{
public List<FileNames> GetFiles()
{
List<FileNames> lstFiles = new List<FileNames>();
DirectoryInfo dirInfo = new DirectoryInfo(HostingEnvironment.MapPath("~/Files"));
int i = 0;
foreach (var item in dirInfo.GetFiles())
{
lstFiles.Add(new FileNames()
{
FileId = i + 1,
FileName = item.Name,
FileSize = item.Length,
FilePath = dirInfo.FullName + @"\" + item.Name,
FileExtension = item.Extension
});
i = i + 1;
}
return lstFiles;
}
}
public class FileNames
{
public int FileId { get; set; }
public string FileName { get; set; }
public long FileSize { get; set; }
public string FilePath { get; set; }
public string FileExtension { get; set; }
}
}
I want to add some code in here to do the conversion to KB, MB, GB, etc. - and I have an idea, but don't know how to incorporate it into what I already have. Here is an example of what I am going for with conversion:
public static string FileSizeFormat(this long FileSize)
{
double size = FileSize;
int index = 0;
for (; size > 1024; index++)
size /= 1024;
return size.ToString("0.00 " + new[] { "B", "KB", "MB", "GB", "TB" }[index]);
}
Any help would be greatly appreciated! I am very new to this and am just stuck on how to blend these two things together. :)
Thank you.
Let me also add the code used in Index.html, maybe that will help complete the circle. I am trying to figure out how to get the formatted file size to show on this page. Thank you.
@using SupportToolkit.Models
@model IEnumerable<SupportToolkit.Models.FileNames>
@{
ViewBag.Title = "Index";
}
<h2>Downloads</h2>
<hr />
<table>
<tr>
<th>
File Name
</th>
<th>
File Size
</th>
</tr>
@foreach (var item in Model)
{
<tr >
<td>
@Html.DisplayFor(modelItem => item.FileName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FileSize)
</td>
<td>
<p style="text-indent: 5em;">
@Html.ActionLink("Download", "Download", new { id = item.FileId })
</p>
</td>
</tr>
}
In this instance, I am using @Html.DisplayFor(modelItem => item.FileSize) to display the file size. But that does not include the formatting. How would I make this the formatted file size (human-readable)?