如果你想用C#来获取你的电脑中存在的所有驱动器,环境类支持GetLogicalDrives()方法。
首先,我们应该看看什么是环境类。
C#中的环境类提供了关于工作环境的信息,如变量、使用的方法和系统相关信息。
让我们通过各自的例子来详细讨论GetLogicalDrives()方法。
Environment.GetLogicalDrives()
C#中的GetLogicalDrives()方法返回我们系统中存在的驱动器。它需要一个字符串数组来存储驱动器。我们可以使用一个foreach循环来逐一显示每个驱动器。
语法
String[] logical_drives_exists = Environment.GetLogicalDrives();
返回类型
它返回字符串的数组。
异常情况
- IO异常- 如果驱动器不存在于我们的系统中,它会返回输入/输出异常。
- SecurityException- 假设有任何安全权限,而用户不能访问相关驱动器,就会发生SecurityException。
例子1:
让我们来显示系统中存在的驱动器。
using System;
class Linuxhint
{
//let's implement the GetLogicalDrives property inside main method
static public void Main()
{
//store the logical drives in an string array
String[] logical_drives_exists = Environment.GetLogicalDrives();
Console.WriteLine("Drives:");
//return all drives one by one
foreach (string each_drive in logical_drives_exists){
Console.WriteLine(each_drive);
}
}
}
输出
Drives:
C:\
D:\
E:\
H:\
例2:
也可以用String.Join()函数从一个字符串数组中一次获得所有的驱动器。
语法
String.Join(",", logical_drives_exists)
using System;
class Linuxhint
{
//let's implement the GetLogicalDrives property inside main method
static public void Main()
{
//store the logical drives in an string array
String[] logical_drives_exists = Environment.GetLogicalDrives();
//return all drives at a time separated by comma
Console.WriteLine("Drives:"+ String.Join(",", logical_drives_exists));
}
}
输出
Drives:C:\,D:\,E:\,H:\
解释一下
第5行
我们在Main方法中实现我们的属性。
第8行
创建一个变量,它是一个用来存储驱动器的字符串数组。
String[] logical_drives_exists = Environment.GetLogicalDrives();
第11行
使用String.Join()函数来返回所有的驱动器。
Console.WriteLine("Drives:"+ String.Join(",", logical_drives_exists));
总结
在这个C#教程中,我们学习了如何使用GetLogicalDrives()方法返回我们系统中存在的驱动器。它需要一个字符串数组来存储驱动器。我们讨论了两个例子,一个是使用for循环一个是使用String.Join()方法获得驱动器,一个是使用字符串获得驱动器。如果有任何安全权限,而用户不能访问驱动器,就会发生SecurityException。