我想使用C#获取任何给定文件的文件大小,如果可能,我需要以GB,MB,KB和字节显示...
对于音频(mp3)文件,我需要获取文件的持续时间......
答案 0 :(得分:6)
您可以使用FileInfo.Length来获取文件的大小(以字节为单位)。然后一个简单的计算可以告诉你KB,MB和GB:
string fileName = "C:\Path\to\file.txt";
var fileInfo = new FileInfo(fileName);
Console.WriteLine("Length = {0} bytes", fileInfo.Length);
Console.WriteLine(" or {0} KB", fileInfo.Length / 1024);
Console.WriteLine(" or {0} MB", fileInfo.Length / 1024 / 1024);
Console.WriteLine(" or {0} GB", fileInfo.Length / 1024 / 1024 / 1024);
要获取mp3文件的持续时间,您需要使用支持读取mp3文件标题的库(例如TagLib#)来解析持续时间。
答案 1 :(得分:1)
试试这个:
public class FileSizeFormatProvider : IFormatProvider, ICustomFormatter
{
public object GetFormat(Type formatType)
{
if (formatType == typeof(ICustomFormatter)) return this;
return null;
}
private const string fileSizeFormat = "fs";
private const Decimal OneKiloByte = 1024M;
private const Decimal OneMegaByte = OneKiloByte * 1024M;
private const Decimal OneGigaByte = OneMegaByte * 1024M;
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (format == null || !format.StartsWith(fileSizeFormat))
{
return defaultFormat(format, arg, formatProvider);
}
if (arg is string)
{
return defaultFormat(format, arg, formatProvider);
}
Decimal size;
try
{
size = Convert.ToDecimal(arg);
}
catch (InvalidCastException)
{
return defaultFormat(format, arg, formatProvider);
}
string suffix;
if (size > OneGigaByte)
{
size /= OneGigaByte;
suffix = "GB";
}
else if (size > OneMegaByte)
{
size /= OneMegaByte;
suffix = "MB";
}
else if (size > OneKiloByte)
{
size /= OneKiloByte;
suffix = "kB";
}
else
{
suffix = " B";
}
string precision = format.Substring(2);
if (String.IsNullOrEmpty(precision)) precision = "2";
return String.Format("{0:N" + precision + "}{1}", size, suffix);
}
private static string defaultFormat(string format, object arg, IFormatProvider formatProvider)
{
IFormattable formattableArg = arg as IFormattable;
if (formattableArg != null)
{
return formattableArg.ToString(format, formatProvider);
}
return arg.ToString();
}
}
在主类中称它为:
public static void Main()
{
FileInfo fInfo = new FileInfo(@"D:\Songs\housefull01(www.songs.pk).mp3");
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "File size: {0:fs}", fInfo.Length));
}
答案 2 :(得分:0)
确定文件大小:
FileInfo fileInfo = new FileInfo(fileName);
Console.WriteLine("Length = " + fileInfo.Length.toString());
您必须根据需要转换该值。