0

I need to set default path of USB drive in C# windows application.

I have tried for get application path and Documents path

string fileName = @"" + Application.StartupPath + "\\Config1.txt";

string folp = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

How to define USB path Like Application Path

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • [https://stackoverflow.com/questions/4437453/path-of-the-usb-devices-which-are-connected-to-the-machine](https://stackoverflow.com/questions/4437453/path-of-the-usb-devices-which-are-connected-to-the-machine) Try to check it. –  Jul 18 '18 at 10:27
  • Thank you this code helps much... – Rajasekaran Bose Jul 18 '18 at 12:46

3 Answers3

1

You could just look for 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");
}

Obviously you have to deal with the case that you have no (or multiple) removable drives, however I'll leave these details up to you.


DriveType Enumeration

Removable

The drive is a removable storage device, such as a floppy disk drive or a USB flash drive.

DriveInfo.GetDrives Method ()

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
1

You can get all removable drives, and then get their drive letter like this:

 foreach (DriveInfo drive in DriveInfo.GetDrives())
 {
     if (drive.DriveType == DriveType.Removable)
     {
        Console.WriteLine(drive.Name);
     }
 }
svdotbe
  • 168
  • 1
  • 3
  • 16
0

You can set the current directory like so:

SetCurrentDirectory("X:\\MyUsbFolder");

See this page for details.

Neil
  • 11,059
  • 3
  • 31
  • 56