简体   繁体   中英

How to transfer the file from Windows Form Application to Xamarin Forms using USB cable C#.net

I am now developing Android Application and the Windows Form.

In the previous, the users need to plug in with USB, copy the file and paste into android folder but it would be troublesome and takes time to do.

How can I transfer the file directly from the PC to android Folder (Internal Storage/ downloads)?

I tried with FolderBrowserDialog to browse and copy into android but "OK" button is disabled when I point the location. enter image description here

Should I write it in Windows Form backend or Xamarin Forms backend side in order to direct transfer into the Android App?

I cannot use Web API as cannot use the inte.net connection.

FolderBrowserDialog dialog = new FolderBrowserDialog();
                
if (dialog.ShowDialog() == DialogResult.OK)
   {
         txtCopy.Text = dialog.SelectedPath;
   }
         string copyFileName = Path.Combine(txtCopy.Text, originalFile); //originalFile->FileName (testing.jpg)

         File.Copy(txtFile1.Text, copyFileName, true);

Direct file transfer from Windows Form and Xamarin Forms by clicking button

Based on your code, I made a Windows Form project to complete the copy.

You could refer to the following code:

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = dialog.SelectedPath;
            }
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.ShowDialog();
            textBox2.Text = dialog.SelectedPath;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DirectoryInfo thefolder = new DirectoryInfo(textBox1.Text);
            foreach (FileInfo nextfile in thefolder.GetFiles()) 
            {
                try
                {
                    string filename = nextfile.Name;
                    string filefullname = nextfile.FullName;
                    string mudi = textBox2.Text + "\\" + filename;
                    if (File.Exists(mudi))
                    {
                        //File.Delete(mudi);
                    }
                    else
                    {
                        File.Copy(filefullname, mudi);
                        MessageBox.Show("Successful");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
    }
}

Now I got it. I have to download MediaDevices framework in NuGet Package Manager to download/ transfer the file from Android device to PC.

I can transfer the file from Android to PC.

But the thing is I cannot transfer/ Upload the file from PC to Android (when using PCToPDA()). When I run the program, the error Director "DT50\Internal shared storage\Download" not found appear even though the directory path is correct.

Any idea why is that happening? 在此处输入图像描述

在此处输入图像描述

    string originalFile;

    private void BtnBrowse_Click(object sender, EventArgs e)
    {
        Browse();     //Get the files from Android Folder
    }

    private void Browse()
    {
        try
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtFile1.Text = openFileDialog1.FileName;

                string fileName = Path.GetDirectoryName(openFileDialog1.FileName);
                originalFile = Path.GetFileName(openFileDialog1.FileName);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Browse-ERR", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void BtnCopy_Click(object sender, EventArgs e)
    {
        PDAToPC();       //Android to PC
        //PCToPDA();       //PC to Android 
    }

    private void PDAToPC()
    {
        try
        {
            string DeviceNameAsSeenInMyComputer = "DT50";

            var devices = MediaDevice.GetDevices();

            using (var device = devices.Where(d => d.FriendlyName == DeviceNameAsSeenInMyComputer || d.Description == DeviceNameAsSeenInMyComputer).First())
            {
                device.Connect();
                var photoDir = device.GetDirectoryInfo(@"\Internal shared storage\Download");
                var files = photoDir.EnumerateFiles("*.*", SearchOption.TopDirectoryOnly);

                
                foreach (var file in files)
                {
                    string destinationFileName = $@"D:\KhineThein\Testing\TransferTesting\photo\{file.Name}";
                    if (!File.Exists(destinationFileName))
                    {
                        using (FileStream fs = new FileStream(destinationFileName, FileMode.Create, System.IO.FileAccess.Write))
                        {
                            device.DownloadFile(file.FullName, fs);
                            
                        }
                    }


                }
                device.Disconnect();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "PDAToPC-ERR", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void PCToPDA()
    {
        try
        {
            string DeviceNameAsSeenInMyComputer = "DT50";
            string tempFileName = "CaptureImport.txt";
            var devices = MediaDevice.GetDevices();

            using (var device = devices.Where(d => d.FriendlyName == DeviceNameAsSeenInMyComputer || d.Description == DeviceNameAsSeenInMyComputer).First())
            {
                device.Connect();
                var photoDir = device.GetDirectoryInfo(@"\Internal shared storage\Download");
                var files = photoDir.EnumerateFiles("*.*", SearchOption.TopDirectoryOnly);

                foreach (var file in files)
                {
                    string originalFileName = $@"D:\KhineThein\Testing\TransferTesting\photo\{tempFileName}";

                    string transferToFileName = $@"{DeviceNameAsSeenInMyComputer}\Internal shared storage\Download\{tempFileName}";

                    using (FileStream fs = new FileStream(originalFileName, FileMode.Open, System.IO.FileAccess.Read))
                    {
                        //device.DownloadFile(file.FullName, fs);                       //Path, Stream
                        device.UploadFile(fs, transferToFileName);                      //Stream, Path
                    }


                }
                device.Disconnect();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "PCToPDA-ERR", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

I too had issues with copying to/from Android with Xamarin. Originally directed to use ADB.exe (Android Debug Bridge), but that had too many security holes / issues and was restricted from using that. Could not use generic 3rd party for other reasons and had to write my own Android / Xamarin file transfer library (works great). One thing I found in MY research was what was the naming convention for paths did not always match what you think it might / should. For example, your "Internal shared storage" wasn't really that when I connected.

"DT50\Internal shared storage\Download" 

it was just

"Internal Storage\Download".  

Did not have a leading \ character and it worked. Writing to other directories, you need to prompt/grant permission on the Xamarin side to look at SOME possible other working folder directories, but that might be something for you at another time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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