C# 获取路径下文件夹的列表 获取文件夹下文件的信息

1.获取某地址下的文件夹名称列表:

//你需要读取的地址信息
string url= “”;
//获取文件地址,此时返回的文件夹包含文件夹的整体路径
string[] directorieStrings = Directory.GetDirectories(url);
//如果需要获取文件夹的名称集合
directorieStrings.Select(d => d.Substring(d.LastIndexOf('\\') + 1)).ToList();
           

关注点:url地址设置,需要设置为本地的地址,不能直接使用网络地址。 

2.获取某文件夹下的所有文件的信息:

//服务器的地址 
string serverPath = "";
//获取文件夹信息
DirectoryInfo directory = new DirectoryInfo(serverPath);

//方式一:
//获取文件下的文件信息
FileInfo[] files = directory.GetFiles();

//此时需要获取文件的路径时,可以通过FileInfo中的FullName属性
//如果只是需要文件的名称时,直接通过FilrInfo中的Name属性

//方式二:
//获取文件的物理路径
string[] files = Directory.GetFiles(serverPath )

关注点:url地址设置,需要设置为本地的地址,不能直接使用网络地址。 

如有疑问,添加微信:18061930825 备注:优快云

### C# 计算目录及其子文件文件夹的总大小 以下是实现计算指定路径文件夹文件的总大小的示例代码: ```csharp using System; using System.IO; public class DirectorySizeCalculator { public static long GetDirectorySize(string directoryPath) { if (!Directory.Exists(directoryPath)) throw new ArgumentException("The specified path does not exist."); long size = 0; try { DirectoryInfo dirInfo = new DirectoryInfo(directoryPath); // Add the sizes of all files within this directory. FileInfo[] fileInfos = dirInfo.GetFiles(); foreach (FileInfo fileInfo in fileInfos) size += fileInfo.Length; // Recursively add the sizes of subdirectories and their contents. DirectoryInfo[] subdirInfos = dirInfo.GetDirectories(); foreach (DirectoryInfo subdirInfo in subdirInfos) size += GetDirectorySize(subdirInfo.FullName); } catch (UnauthorizedAccessException ex) { Console.WriteLine($"Access denied to some directories or files: {ex.Message}"); } return size; } public static void Main() { string targetPath = @"C:\Your\Target\Folder"; // Replace with your desired folder path. try { long totalBytes = GetDirectorySize(targetPath); double megabytes = totalBytes / (double)(1 << 20); // Convert bytes into MBs. Console.WriteLine($"Total Size of '{targetPath}': {megabytes:F2} MB"); } catch (Exception ex) { Console.WriteLine($"An error occurred while calculating the directory size: {ex.Message}"); } } } ``` 上述代码通过递归方式遍历目标目录下的所有文件和子目录,累加它们各自的字节长度以得出最终的总大小。如果遇到权限不足的情况,则会捕获 `UnauthorizedAccessException` 并打印错误消息。 此方法利用了 .NET 的 `System.IO` 命名空间中的类来操作文件系统对象[^1]。对于每个目录,先获取其内部的所有文件并统计它们的大小;接着再对每一个子目录重复这一过程直到完成整个树形结构的扫描。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值