Converts a number of bytes to a shorter, more readable string representation : File Command « File Stream « C# / C Sharp






Converts a number of bytes to a shorter, more readable string representation

     
/* Copyright (c) 2010 Michael Lidgren

Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;

namespace Lidgren.Network
{
  /// <summary>
  /// Utility methods
  /// </summary>
  public static class NetUtility
  {
    /// <summary>
    /// Converts a number of bytes to a shorter, more readable string representation
    /// </summary>
    public static string ToHumanReadable(long bytes)
    {
      if (bytes < 4000) // 1-4 kb is printed in bytes
        return bytes + " bytes";
      if (bytes < 1000 * 1000) // 4-999 kb is printed in kb
        return Math.Round(((double)bytes / 1000.0), 2) + " kilobytes";
      return Math.Round(((double)bytes / (1000.0 * 1000.0)), 2) + " megabytes"; // else megabytes
    }

  }
}

   
    
    
    
    
  








Related examples in the same category

1.C# Implementation of the File Copy Command
2.Use the FileInfo Class to Delete Files with Ease
3.File Move Implementation
4.Rename File Name
5.Rename File Extension
6.Backup File
7.Copy directory
8.Find string in a file
9.Compares the specified file1. This method accepts two strings the represent two files to compare.
10.File Renamer
11.Format File Size
12.Is File Existed
13.Is File readable or writeable
14.Replace in file
15.Send a file to the recycle bin
16.Copy file and folder
17.Gets last write time for a file.
18.Execute File
19.Gets the file size text.
20.Get File Bytes And Readable Size Information
21.Copy folder
22.Empty a Folder