How to enter a upload form within my C# windows fo

2019-09-15 13:44发布

问题:

I have a webpage with a file upload dialog. I'm viewing this page from my WebBrowser control in my Windows Forms application. I'd like to automatically enter and submit the form.

I realise this question has been asked before (a lot). I've seen so many of them I lost the count. But none of the solutions have worked for me.

My Webpage looks like

<form method="post" enctype="multipart/form-data">
   <input id="file" name="file" type="file"/>
   <input type="submit"/>
</form

My C# application looks like

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        webBrowser1.Document.GetElementById("file").Focus();
        SendKeys.Send("C:\\Users\\Merlin Sweden\\Desktop\\extraDirTest\\myImage.jpg{ENTER}");
    }
}

From all the things I've tried this at least felt like I was getting close. Anyway, when executing the dialog opens and part of the path is entered (weden\Desktop\extraDirTest\myImage.jpg). I thought it might be some sort of maximum input length, I've added another directory in the path (extraDirTest) and discovered that that was not the issue.

So I'm thinking it is related to the space BUT i cannot find any alternative to enter a space. Also if the PATH i send is incorrect the dialog doesn't open at all. And if i place a textbox on my form and try to enter it in there then all works fine.

I don't understand what is happening or how I should fix this.

Can anyone help me?

Thank you

Edit Perhaps it is worth mentioning that moving the file to "C:\myImage.jpg" and changing the path doesn't do anything.

回答1:

The reason only half of it is entered is because the 'focus' does not trigger the dialog. The space does. So the dialog is only opened after the space and whatever is sent after that it entered.

For some reason the character right after the space is also left out, probably related to timing.

I've ended up doing

SendKeys.Send("  C:\\extraDirTest\\sednasoftwaread.jpg{ENTER}");

Also afterwards you cannot instantly submit the form because then the form will be submitted before the input is filled. Sleeping also isn't the answer because the dialog sleeps along. Using a timer the form can be submitted after the input has been entered.

Everyone thank you for the help!