PT
C# / .NET - obter tamanho do arquivo
3 points
Neste artigo, veremos como obter o tamanho do arquivo em C # / .NET.
Visão geral rápida:
xxxxxxxxxx
1
FileInfo file = new FileInfo(@"C:\path\to\file.txt"); // using System.IO;
2
int fileSize = file.Length;
Veja o código abaixo para ver um exemplo prático de uso:
Na solução apresentada, a classe FileInfo
foi usada com a propriedade Length
que retorna o tamanho do arquivo.
Nota: se o arquivo foi modificado após a criação do objeto
FileInfo
, o métodoRefresh()
deve ser chamado no objeto para obter as informações atuais do arquivo.
xxxxxxxxxx
1
using System;
2
using System.IO;
3
4
public static class Program
5
{
6
public static void Main(string[] args)
7
{
8
string path = @"C:\path\to\file.txt";
9
10
FileInfo info = new FileInfo(path);
11
Console.WriteLine("File size: " + info.Length + " bytes");
12
}
13
}
Resultado:
xxxxxxxxxx
1
File size: 46 bytes
Em alguns casos, quando usamos a propriedade Length
com stream específico, precisamos ter certeza de que a propriedade está implementada - para o método File.Open
, o resultado é:
Nota: essa abordagem é útil quando abrimos o stream.
xxxxxxxxxx
1
using System;
2
using System.IO;
3
4
public class Program
5
{
6
public static void Main(string[] args)
7
{
8
string path = @"C:\path\to\file.txt";
9
10
using (FileStream stream = File.Open(path, FileMode.Open))
11
{
12
Console.WriteLine("File size: " + stream.Length + " bytes");
13
}
14
}
15
}
Resultado:
xxxxxxxxxx
1
File size: 46 bytes