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