在C#中獲取文件大小的多種方法
在C#中獲取文件大小有多種方法,以下是幾種常用的方式:
1. 使用FileInfo類(lèi)(最常用)
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = @"C:\example\file.txt";
// 方法1:使用FileInfo
FileInfo fileInfo = new FileInfo(filePath);
if (fileInfo.Exists)
{
// 獲取文件大小(字節(jié))
long fileSizeInBytes = fileInfo.Length;
Console.WriteLine($"文件大?。ㄗ止?jié)): {fileSizeInBytes} B");
// 轉(zhuǎn)換為更友好的格式
Console.WriteLine($"文件大?。↘B): {fileSizeInBytes / 1024.0:F2} KB");
Console.WriteLine($"文件大?。∕B): {fileSizeInBytes / (1024.0 * 1024):F2} MB");
}
else
{
Console.WriteLine("文件不存在!");
}
}
}
2. 使用File靜態(tài)類(lèi)
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = @"C:\example\file.txt";
if (File.Exists(filePath))
{
FileInfo fileInfo = new FileInfo(filePath);
long fileSize = fileInfo.Length;
Console.WriteLine($"文件大小: {fileSize} 字節(jié)");
}
}
}
3. 使用FileStream獲取文件大小
using System;
using System.IO;
class Program
{
static void Main()
{
string filePath = @"C:\example\file.txt";
try
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
long fileSize = fs.Length;
Console.WriteLine($"文件大小: {fileSize} 字節(jié)");
}
}
catch (FileNotFoundException)
{
Console.WriteLine("文件不存在!");
}
}
}
4. 完整的工具類(lèi)示例
using System;
using System.IO;
public class FileSizeHelper
{
/// <summary>
/// 獲取文件大小(字節(jié))
/// </summary>
public static long GetFileSizeInBytes(string filePath)
{
if (!File.Exists(filePath))
throw new FileNotFoundException($"文件不存在: {filePath}");
return new FileInfo(filePath).Length;
}
/// <summary>
/// 獲取格式化后的文件大小字符串
/// </summary>
public static string GetFormattedFileSize(string filePath)
{
long bytes = GetFileSizeInBytes(filePath);
return FormatFileSize(bytes);
}
/// <summary>
/// 格式化文件大小
/// </summary>
public static string FormatFileSize(long bytes)
{
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
int order = 0;
double size = bytes;
while (size >= 1024 && order < sizes.Length - 1)
{
order++;
size = size / 1024;
}
return $"{size:0.##} {sizes[order]}";
}
}
// 使用示例
class Program
{
static void Main()
{
string filePath = @"C:\example\file.txt";
try
{
long sizeInBytes = FileSizeHelper.GetFileSizeInBytes(filePath);
string formattedSize = FileSizeHelper.FormatFileSize(sizeInBytes);
Console.WriteLine($"文件大?。ㄗ止?jié)): {sizeInBytes}");
Console.WriteLine($"格式化后: {formattedSize}");
// 直接獲取格式化大小
Console.WriteLine($"文件大小: {FileSizeHelper.GetFormattedFileSize(filePath)}");
}
catch (Exception ex)
{
Console.WriteLine($"錯(cuò)誤: {ex.Message}");
}
}
}
5. 異步獲取文件大小
using System;
using System.IO;
using System.Threading.Tasks;
public class AsyncFileSizeHelper
{
public static async Task<long> GetFileSizeAsync(string filePath)
{
return await Task.Run(() =>
{
if (!File.Exists(filePath))
throw new FileNotFoundException($"文件不存在: {filePath}");
return new FileInfo(filePath).Length;
});
}
}
// 使用示例
class Program
{
static async Task Main()
{
string filePath = @"C:\example\file.txt";
try
{
long fileSize = await AsyncFileSizeHelper.GetFileSizeAsync(filePath);
Console.WriteLine($"文件大小: {FileSizeHelper.FormatFileSize(fileSize)}");
}
catch (Exception ex)
{
Console.WriteLine($"錯(cuò)誤: {ex.Message}");
}
}
}
注意事項(xiàng)
- 文件存在性檢查:在獲取文件大小前,應(yīng)先檢查文件是否存在
- 權(quán)限問(wèn)題:確保程序有讀取文件的權(quán)限
- 大文件處理:對(duì)于非常大的文件(超過(guò)2GB),確保使用
long類(lèi)型 - 路徑格式:注意文件路徑中的特殊字符和路徑分隔符
- 異常處理:建議使用try-catch處理可能的異常
性能建議
- 對(duì)于頻繁獲取文件大小的場(chǎng)景,建議使用
FileInfo并緩存實(shí)例 - 異步方法適合在UI應(yīng)用程序中使用,避免界面卡頓
- 對(duì)于網(wǎng)絡(luò)文件,需要考慮網(wǎng)絡(luò)延遲和超時(shí)設(shè)置
選擇哪種方法取決于具體需求。FileInfo是最常用且性能較好的方法。
以上就是在C#中獲取文件大小的多種方法的詳細(xì)內(nèi)容,更多關(guān)于C#獲取文件大小的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
基于C#的音樂(lè)播放器主Form實(shí)現(xiàn)代碼
這篇文章主要介紹了基于C#的音樂(lè)播放器主Form實(shí)現(xiàn)代碼,很實(shí)用的功能,需要的朋友可以參考下2014-08-08
C# FileSystemWatcher 在監(jiān)控文件夾和文件時(shí)的使用方法
這篇文章主要介紹了C# FileSystemWatcher 在監(jiān)控文件夾和文件時(shí)的使用方法,文中講解非常細(xì)致,代碼幫助大家更好的理解和學(xué)習(xí),感興趣的朋友可以參考下2020-06-06
一文帶你快速學(xué)會(huì)C#中WinForm框架的使用詳解
WinForm是一門(mén)非常經(jīng)濟(jì)實(shí)惠的技術(shù),就是說(shuō),可以在短時(shí)間內(nèi)學(xué)會(huì),并迅速借此進(jìn)行項(xiàng)目開(kāi)發(fā)。本文就來(lái)和大家聊聊WinForm框架的使用方法,希望對(duì)大家有所幫助2023-02-02
unity實(shí)現(xiàn)方向盤(pán)轉(zhuǎn)動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了unity實(shí)現(xiàn)方向盤(pán)轉(zhuǎn)動(dòng)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
C#反射調(diào)用拓展類(lèi)方法實(shí)例代碼
這篇文章主要給大家介紹了關(guān)于C#反射調(diào)用拓展類(lèi)方法的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-01-01
c#打印預(yù)覽控件中實(shí)現(xiàn)用鼠標(biāo)移動(dòng)頁(yè)面功能代碼分享
項(xiàng)目中需要實(shí)現(xiàn)以下功能:打印預(yù)覽控件中,可以用鼠標(biāo)拖動(dòng)頁(yè)面,以查看超出顯示范圍之外的部分內(nèi)容,下面就是實(shí)現(xiàn)代碼2013-12-12
C#表達(dá)式樹(shù)Expression動(dòng)態(tài)創(chuàng)建表達(dá)式
這篇文章介紹了C#表達(dá)式樹(shù)Expression動(dòng)態(tài)創(chuàng)建表達(dá)式的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12

