简体   繁体   English

如何获取 U 盘的路径

[英]How to get the path for a usb flash drive

I made this code where it copies a file on my computer to the USB attached to the before mention computer.我制作了这段代码,它将我计算机上的文件复制到连接到前面提到的计算机的 USB 中。 Here is my code:这是我的代码:

            FileInfo file = new FileInfo(all_path);

            file.CopyTo(@"E:\tst\test\testing");

When I try using this on a another computer, it does not work because on that computer the USB is af:\\ drive and on my computer it is a E:\\ drive.当我尝试在另一台计算机上使用它时,它不起作用,因为在该计算机上 USB 是 af:\\ 驱动器,而在我的计算机上它是 E:\\ 驱动器。 So how do I make it that the code works on every computer.那么我如何使代码在每台计算机上都能运行。 I hope someone can help me我希望有一个人可以帮助我

The class you'd want to use to develop your solution is the DriveInfo class.您想用来开发解决方案的类是DriveInfo类。 There is no way to guarantee it's the same drive easily but you can use options such as the DriveType property to check it's a removable USB drive or the VolumeLabel if you're trying to make it only use one USB stick.无法轻松保证它是同一个驱动器,但您可以使用 DriveType 属性等选项来检查它是可移动 USB 驱动器,或者如果您试图使其仅使用一个 USB 记忆棒,则使用 VolumeLabel。

        DriveInfo[] allDrives = DriveInfo.GetDrives();
        foreach (DriveInfo d in allDrives)
        {
            if (d.DriveType == DriveType.Removable && d.VolumeLabel == "MyVolumeLabel")
            {
                FileInfo file = new FileInfo(all_path);
                file.CopyTo(d.Name + @"\tst\test\testing");
            }                    

        }

If your application is running from the stick get your path like described here:如果您的应用程序从棒上运行,请获取您的路径,如下所述:

get path for my .exe 获取我的 .exe 的路径

other option is to check the name of you device.另一个选项是检查您的设备名称。 Use the code described here:使用此处描述的代码:

Path of the USB devices which are connected to the machine? 连接到机器的 USB 设备的路径?

How to detect a USB drive has been plugged in? 如何检测USB驱动器已插入?

This can help you.这可以帮助你。

When you find Removable Drives you can query all files to find which you want.当您找到可移动驱动器时,您可以查询所有文件以找到您想要的文件。

Or if you will you the same drive all the time, you can use DriveInfo.Name property.或者,如果您始终使用相同的驱动器,则可以使用 DriveInfo.Name 属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM