C#:USB 密钥的路径

C# : Path of an USB key

我编写了一个小程序来将数据备份到txt,只是最终目标是将txt 保存在U 盘上。

此 USB 密钥将包含软件和 txt。 我唯一的问题是如何知道方式,想象一下它可以有几个U盘连接到电脑?

代码:

   string path = System.IO.Path.Combine (Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments), "Tableau.txt");

如果像我在本例中所做的那样将 USB 命名为 'BAKUP-USB' 之类的名称,您可以在所有连接的设备中搜索它。之后,您可以获得所需的 USB 路径。

希望这至少能给您一些帮助。

DriveInfo[] mydrives = DriveInfo.GetDrives();
foreach (DriveInfo mydrive in mydrives)
{
    //Check for removable devices like USB's
    if (mydrive.DriveType == DriveType.Removable) 
    {
        //Check for that specific USB
        if (mydrive.VolumeLabel.Equals("BAKUP-USB")) 
        {
            DirectoryInfo path = mydrive.RootDirectory;
            Path.GetFullPath(path.ToString());
        } 
    }
}

如果你想保存到你的项目文件夹(无论它在哪里),使用 "C:" 不带反斜杠。

  using(TextReader tr = new StreamReader(@"C:MyText.txt")){
     tr.ReadAllLines();
  }

将从您的项目文件夹中读取文件 "MyText.txt",无论它位于 c:\Documents\Visual Studio.... 还是 x:\USB\MyProgram..."