C#定义USB路径
C# define USB path
我需要在 C# windows 应用程序中设置 USB 驱动器的默认路径。
我已经尝试获取应用程序路径和文档路径
string fileName = @"" + Application.StartupPath + "\Config1.txt";
string folp = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
如何定义USB路径 Like Application Path
您可以像这样设置当前目录:
SetCurrentDirectory("X:\MyUsbFolder");
详情见this page。
您可以只查找 DriveType.Removable
with DriveInfo.GetDrives
var removableDrives = DriveInfo.GetDrives()
.Where(x => x.DriveType == DriveType.Removable)
.Select(x => x.RootDirectory)
.ToList();
if (removableDrives.Any())
{
string myPath = Path.Combine(removableDrives[0].FullName, "Config1.txt");
}
显然,您必须处理没有(或多个)可移动驱动器的情况,但我会将这些细节留给您。
Removable
The drive is a removable storage device, such as a floppy disk drive
or a USB flash drive.
Retrieves the drive names of all logical drives on a computer
Remarks
This method retrieves all logical drive names on a computer. You can
use this information to iterate through the array and obtain
information on the drives using other DriveInfo methods and
properties. Use the IsReady property to test whether a drive is ready
because using this method on a drive that is not ready will throw a
IOException.
您可以获得所有可移动驱动器,然后像这样获取它们的盘符:
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.DriveType == DriveType.Removable)
{
Console.WriteLine(drive.Name);
}
}
我需要在 C# windows 应用程序中设置 USB 驱动器的默认路径。
我已经尝试获取应用程序路径和文档路径
string fileName = @"" + Application.StartupPath + "\Config1.txt";
string folp = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
如何定义USB路径 Like Application Path
您可以像这样设置当前目录:
SetCurrentDirectory("X:\MyUsbFolder");
详情见this page。
您可以只查找 DriveType.Removable
with DriveInfo.GetDrives
var removableDrives = DriveInfo.GetDrives()
.Where(x => x.DriveType == DriveType.Removable)
.Select(x => x.RootDirectory)
.ToList();
if (removableDrives.Any())
{
string myPath = Path.Combine(removableDrives[0].FullName, "Config1.txt");
}
显然,您必须处理没有(或多个)可移动驱动器的情况,但我会将这些细节留给您。
Removable
The drive is a removable storage device, such as a floppy disk drive or a USB flash drive.
Retrieves the drive names of all logical drives on a computer
Remarks
This method retrieves all logical drive names on a computer. You can use this information to iterate through the array and obtain information on the drives using other DriveInfo methods and properties. Use the IsReady property to test whether a drive is ready because using this method on a drive that is not ready will throw a IOException.
您可以获得所有可移动驱动器,然后像这样获取它们的盘符:
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.DriveType == DriveType.Removable)
{
Console.WriteLine(drive.Name);
}
}