sebnilsson.com | Liquid Development Is What I Do
Seb Nilsson

Create Human-Readable File Size Strings in C#

After needing functionality in C# for getting a human-readable file-size string I posted a question about it on Stackoverflow, as one does.

The accepted answer had about 72 lines of code. One explanation for this could be that I did specify that I wanted the solution to implement IFormatProvider. Not sure why I did that, probably seemed right at the time, in the end of 2008.

One creative solution was to use a Win32 API call to StrFormatByteSizeA

[DllImport("Shlwapi.dll", CharSet = CharSet.Auto)]
    public static extern long StrFormatByteSize(long fileSize, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer, int bufferSize);

Compact, clean, cross-platform solution

For the sake of simplicity, readability and the bonus of cross-platform I re-implemented an earlier solution I found, that was written in JavaScript. But the solution was easily translateble into C#.

public static class FileSizeHelper
{
    private static readonly string[] Units = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

    private static string GetReadableFileSize(long size) // Size in bytes
    {
        int unitIndex = 0;
        while (size >= 1024)
        {
            size /= 1024;
            ++unitIndex;
        }

        string unit = Units[unitIndex];
        return string.Format("{0:0.#} {1}", size, unit);
    }
}

FTP Upload File Using Only .NET Framework

Here an example of how to upload a file to a FTP-server, using the class FtpWebRequest, which is included in the .NET Framework.

string ftpPath = string.Format("ftp://{0}/{1}", urlOrIpNumber, filePath);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpPath);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential (userName, password);

byte[] fileContents = GetFileContent();
request.ContentLength = fileContents.Length;

using(var requestStream = request.GetRequestStream())
{
    requestStream.Write(fileContents, 0, fileContents.Length);
    requestStream.Close();
}

All you need to do is reference the System.Net namespace.

Update: Shorter code version

This code comes from Mads Kristensen, written in the middle of 2006.

private static void Upload(string ftpServer, string userName, string password, string filename)
{
   using (var client = new WebClient())
   {
      client.Credentials = new NetworkCredential(userName, password);
      client.UploadFile(ftpServer + "/" + new FileInfo(filename).Name, "STOR", filename);
   }
}

I'm not sure if there are any scenarios that this code doesn't work with.