16

I have been researching this topic for days and I can't find anything on managing files on a MTP Portable Device (More specifically a Galaxy S4).

I want to be able to...

  • Copy files from the PC to the MTP Device
  • Copy files from the MTP Device to the PC
  • Delete files from the MTP Device

I really want to copy MP3 files but if there is a general way to copy over and file supported by MTP that would be awesome. I've looked into the Window Portable Device API but I couldn't find anywhere where there is sample code in C#.

Any blogs, sample code, and files would be very helpful. Thanks! :)

xChris6041x
  • 179
  • 1
  • 1
  • 8

2 Answers2

13

I used a nugetpackage called MediaDevices

this made it very easy for me to copy my photos from my android phone to my computer.

 public class Program
{
    static void Main(string[] args)
    {
        var devices = MediaDevice.GetDevices();
        using (var device = devices.First(d => d.FriendlyName == "Galaxy Note8"))
        {
            device.Connect();
            var photoDir = device.GetDirectoryInfo(@"\Phone\DCIM\Camera");

            var files = photoDir.EnumerateFiles("*.*", SearchOption.AllDirectories);

            foreach (var file in files)
            {
                MemoryStream memoryStream = new System.IO.MemoryStream();
                device.DownloadFile(file.FullName, memoryStream);
                memoryStream.Position = 0;
                WriteSreamToDisk($@"D:\PHOTOS\{file.Name}", memoryStream);
            }
            device.Disconnect();
        }

    }

    static void WriteSreamToDisk(string filePath, MemoryStream memoryStream)
    {
        using (FileStream file = new FileStream(filePath, FileMode.Create, System.IO.FileAccess.Write))
        {
            byte[] bytes = new byte[memoryStream.Length];
            memoryStream.Read(bytes, 0, (int)memoryStream.Length);
            file.Write(bytes, 0, bytes.Length);
            memoryStream.Close();
        }
    }
}
Deanna
  • 23,876
  • 7
  • 71
  • 156
ZackOfAllTrades
  • 567
  • 5
  • 12
  • doesnnt work.. Error CS0117 'MediaDevice' does not contain a definition for 'GetDevices' – eMi Sep 23 '22 at 18:01
  • This nuget package works great for me, glad I found this article. One issue I had with very large video files was using MemoryStream, i.e. allocating byte[] bytes would fail, etc. But then I found that another instance of DownloadFile(string source, string destination) writes directly to file - exactly what I needed. The package comes with a nice CHM manual conveniently installed in the project hierarchy. – sun2sirius Dec 04 '22 at 19:24
1

There is also a nuget package called WPDApi which worked well for me, after I managed to download the source code (had problems with nuget):

https://github.com/Duke-fleed/WPDApi

Florian Straub
  • 826
  • 9
  • 18