File size
In this chapter you will learn:
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:
Home » C# Tutorial » File, Path