This article is a mirror article of machine translation, please click here to jump to the original article.

View: 21011|Reply: 0

[Source] C# gets the file size

[Copy link]
Posted on 3/24/2016 5:14:17 PM | | |

Of course, you need to introduce System.IO namespace

The first one:

public static long GetDirectoryLength(string dirPath)
{
Determine if a given path exists and exit if it does not
if (! Directory.Exists(dirPath))
return 0;
long len = 0;

//定义一个DirectoryInfo对象
DirectoryInfo di = new DirectoryInfo(dirPath);

Use the GetFiles method to get the size of all files in the di directory
foreach (FileInfo fi in di.GetFiles())
{
len += fi. Length;
}

Get all the folders in the di and save them to a new array of objects for recursion
DirectoryInfo[] dis = di.GetDirectories();
if (dis. Length > 0)
{
for (int i = 0; i < dis. Length; i++)
{
len += GetDirectoryLength(dis. FullName);
}
}
return len;
}

The second

It also uses the idea of recursion, but it is judged by the Exits method of the File class

//所给路径中所对应的是否为文件

public static long FileSize(string filePath)
{
long temp = 0;

//判断当前路径所指向的是否为文件
if (File.Exists(filePath) == false)
{
string[] str1 = Directory.GetFileSystemEntries(filePath);
foreach (string s1 in str1)
{
temp += FileSize(s1);
}
}
else
{

Define a FileInfo object to associate it with the file direction pointed to by the filePath,

//以获取其大小
FileInfo fileInfo = new FileInfo(filePath);
return fileInfo.Length;
}
return temp;
}

In fact, the idea of deleting a folder is the same as this, the setting is much simpler, just simply judge whether it is a file or a folder, if it is a file, delete it. If it is a folder, it is recursive




Previous:The HTTP request in C# get, post comes with a retry parameter
Next:Similarities and differences between Winform and WPF selection folder dialogs
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com