How to Get the File Size in C#

How do you get the file size in C#?

FileInfo.Length will return the length of file, in bytes (not size on disk), so this is what you are looking for, I think.

C# Get file size

Check your permission to the folder first. If you don't have permission to the folder, then the file operation won't work:

using System.IO;
static long GetFileSize(string FilePath)
{
//if you don't have permission to the folder, Directory.Exists will return False
if(!Directory.Exists(Path.GetDirectoryName(FilePath))
{
//if you land here, it means you don't have permission to the folder
Debug.Write("Permission denied");
return -1;
}
else if(File.Exists(FilePath))
{
return new FileInfo(FilePath).Length;
}
return 0;
}

Read more: Read Permissions to a directory in C#

C# Get file size of array with paths

If i understand you correctly, just use Linq Select and string.Join

var results = Directory.GetFiles(Path, "*" + filetype, SearchOption.AllDirectories)
.Select(file => new FileInfo(file).Length);

TextBox1.Text = string.Join(", ", results);

if you want to sum them, just use Enumerable.Sum

 TextBox1.Text = $"{results.Sum():N3}";

Update

public static class MyExtension
{
public enum SizeUnits
{
Byte, KB, MB, GB, TB, PB, EB, ZB, YB
}

public static string ToSize(this Int64 value, SizeUnits unit)
{
return (value / (double)Math.Pow(1024, (Int64)unit)).ToString("0.00");
}
}

TextBox1.Text = results.Sum().ToSize();

How do i get single file size?

For some reason the static class File does not contain a Size(String fileName) method, instead you need to do it this way:

Int64 fileSizeInBytes = new FileInfo(fileName).Length;

Regarding performance:

Don't worry about the new FileInfo allocation:

  • FileInfo does not own any unmanaged resources (i.e. it's not IDisposable)
  • FileInfo's constructor is cheap: The constructor simply gets the normalized path via Path.GetFullPath and performs a FileIOPermission - it stores the normalized path as a .NET String in an instance field.

Most of the work is inside the Length property getter: itself is a wrapper around Win32's GetFileAttributesEx - so the operations performed are almost identical to what it would be if it were a static utility method.

As the new FileInfo object is short-lived it means the GC will collect it quickly as a Generation 0 object. The overhead of a couple of strings (FileInfo's fields) on the heap really is negligible.

Getting the file size of a file in C#

FileInfo asks the filesystem for the file size information (it does not need to read all of the contents to do so of course). This is usually considered an "expensive" operation (in comparison to manipulating stuff in memory and calling methods) because it hits the disk.

However, while it's true that cutting down on disk accesses is a good thing, when you are preparing to read the full contents of a file anyway this won't make a difference in the grand scheme of things. So the performance of FileInfo itself is what you should be focusing on.

The #1 performance issue here is that the first approach keeps the whole file in memory for as long as the client takes to download it -- this can be a huge problem, as (depending on the size of the files and the throughput of the client connection) it has the potential of massively increasing the memory usage of your application. And if this increased memory usage leads to swapping (i.e. hitting the disk) performance will instantly tank.

So what you should do is use TransmitFile -- not because it's faster when going to the disk (it may or may not be), but because it uses less memory.

How to get Size of file in FileInfo?

You are using fileInfos, which is a List<T>. You want to check the length of your actual FileInfo f:

long s1 = f.Length;

While you are dividing by 1024, please note, that there is a difference in units when dealing with filezises, depending on your base: 2 or 10. KB is 2^x and kB is 10^x bytes.

Get file size from text file

You can get information about a file -- including its size -- with the FileInfo class

e.g.

var fileName = @"C:\Locations2.txt";
FileInfo fi = new FileInfo(fileName);
var size = fi.Length;
Console.WriteLine("File Size in Bytes: {0}", size);

The code you had above that you put inside the loop is the right concept, just the wrong implementation. If you know the file name you want to open, no need to go through the DirectoryInfo.GetFiles route. Just access the FileInfo directly.

So your code would look something like this:

static void Main(string[] args)
{

string[] lines = System.IO.File.ReadAllLines(@"C:\Locations2.txt");
foreach (string path in lines)
if (File.Exists(path))
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Results.txt", true))
{
file.WriteLine("File found" + "\t" + path);
Console.WriteLine("File found" + "\t" + path);

FileInfo fi = new FileInfo(path);
var size = fi.Length;
file.WriteLine("File Size in Bytes: {0}", size);
Console.WriteLine("File Size in Bytes: {0}", size);
}

else
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Results.txt", true))
{
file.WriteLine("Does not Exist" + "\t" + path);
Console.WriteLine("Does not Exist" + "\t" + path);
}

}

ASP.NET: Fast way to get file size and count of all files?

Try dumping recursion, and try dumping linq - it is slow and eats up a lot of memory.

Try this:

  Dim strFolder = "C:\Users\AlbertKallal\Desktop"

Dim MyDir As New DirectoryInfo(strFolder)
Dim MyFiles() As FileInfo = MyDir.GetFiles("*.*", SearchOption.AllDirectories)

For Each MyFile As FileInfo In MyFiles
tSize += MyFile.Length
Next

Get size of file on disk

This uses GetCompressedFileSize, as ho1 suggested, as well as GetDiskFreeSpace, as PaulStack
suggested, it does, however, use P/Invoke. I have tested it only for compressed files, and I suspect it does not work for fragmented files.

public static long GetFileSizeOnDisk(string file)
{
FileInfo info = new FileInfo(file);
uint dummy, sectorsPerCluster, bytesPerSector;
int result = GetDiskFreeSpaceW(info.Directory.Root.FullName, out sectorsPerCluster, out bytesPerSector, out dummy, out dummy);
if (result == 0) throw new Win32Exception();
uint clusterSize = sectorsPerCluster * bytesPerSector;
uint hosize;
uint losize = GetCompressedFileSizeW(file, out hosize);
long size;
size = (long)hosize << 32 | losize;
return ((size + clusterSize - 1) / clusterSize) * clusterSize;
}

[DllImport("kernel32.dll")]
static extern uint GetCompressedFileSizeW([In, MarshalAs(UnmanagedType.LPWStr)] string lpFileName,
[Out, MarshalAs(UnmanagedType.U4)] out uint lpFileSizeHigh);

[DllImport("kernel32.dll", SetLastError = true, PreserveSig = true)]
static extern int GetDiskFreeSpaceW([In, MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName,
out uint lpSectorsPerCluster, out uint lpBytesPerSector, out uint lpNumberOfFreeClusters,
out uint lpTotalNumberOfClusters);


Related Topics



Leave a reply



Submit