File size

In this chapter you will learn:

  1. How to get the file size
  2. Format File Size

Get the file size

using System;//j a va 2  s. c  om
using System.IO;

class MainClass
{
    public static void Main(string[] args)
    {
        FileInfo file = new FileInfo("c:\\test.txt");

        Console.WriteLine("Checking file: " + file.Name);
        Console.WriteLine("File exists: " + file.Exists.ToString());

        if (file.Exists)
        {
            Console.Write("File size (bytes): ");
            Console.WriteLine(file.Length.ToString());
            Console.Write("File attribute list: ");
            Console.WriteLine(file.Attributes.ToString());
        }

    }
}

The code above generates the following result.

Format File Size

using System;//from java  2s .  co m
using System.Collections.Generic;
using System.Text;


static class Utils
{
    private static readonly double kilobyte = 1024;
    private static readonly double megabyte = 1024 * kilobyte;
    private static readonly double gigabyte = 1024 * megabyte;
    private static readonly double terabyte = 1024 * gigabyte;

    public static string FormatFileSize(double bytes)
    {
        if (bytes > terabyte) return (bytes / terabyte).ToString("0.00 TB");
        else if (bytes > gigabyte) return (bytes / gigabyte).ToString("0.00 GB");
        else if (bytes > megabyte) return (bytes / megabyte).ToString("0.00 MB");
        else if (bytes > kilobyte) return (bytes / kilobyte).ToString("0.00 KB");
        else return bytes + " bytes";
    }
}

Next chapter...

What you will learn in the next chapter:

  1. How to use FileAttributes enumeration
  2. ReadOnly file attribute
Home » C# Tutorial » File, Path
File creation
Deleting Files
Put to recycle bin
File Exists
File moving
File size
File attribute
Set file attribute
File time change
File time
Random file name
Temporary file
Path
Directory creation
Delete directory
Path existance
Change the path
Current Path
Directory listing
Recursive Path Listing
Combine path
Calculate Directory Size
Invalid path characters
System path
Directory copy
Drive
Drive information
File access rule
File System watcher