C # get File size

Source: Internet
Author: User

Of course, we need to introduce the System.IO namespace.

The first one:

public static long Getdirectorylength (string dirpath)
{
Determines whether a given path exists and exits if it does not exist
if (! Directory.Exists (Dirpath))
return 0;
Long len = 0;

Define a DirectoryInfo object
DirectoryInfo di = new DirectoryInfo (Dirpath);

Get the size of all files in the Di directory through the GetFiles method
foreach (FileInfo fi in Di. GetFiles ())
{
Len + = fi. Length;
}

Get all the folders in Di and coexist in a new object array for recursion
directoryinfo[] dis = di. GetDirectories ();
if (DIS. Length > 0)
{
for (int i = 0; i < dis. Length; i++)
{
Len + = getdirectorylength (dis. FullName);
}
}
return Len;
}

A second

It is also the idea of using recursion, only to judge by the exits method of the file class.

Whether the corresponding file is in the given path

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

Determines whether the current path points to a file
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 with the file that FilePath points to,

To get its size
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, as long as the simple to determine whether the current file or folder, if the file is deleted. It's a folder. Recursion

C # get File size

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.