Saturday, May 30, 2009

Uploading Files using Selenium RC in C#

After googling all around to overcome the Selenium incapability of handling File Upload control finally I could write a simple function in C# which will do my job. In the function given below _selObj is the object of DefaultSelenium class.

public bool TypeIntoFileUpload(string controlId, string filePath)
{
    try
    {
        string newFilePath = filePath.Replace('\\', '/');
         _selObj.WindowFocus();
         _selObj.Focus(controlId);
        string jscript="";
        jscript += "if(selenium.browserbot.getCurrentWindow().clipboardData){window.clipboardData.setData('Text','" + newFilePath + "');}";
         _selObj.GetEval(jscript);
        byte VK_CONTROL = 0x11;
        byte VK_V = 0x56;
        _selObj.KeyDownNative(Convert.ToString(VK_CONTROL));
        _selObj.KeyPressNative(Convert.ToString(VK_V));
        _selObj.KeyUpNative(Convert.ToString(VK_CONTROL));

        return true;
    }
    catch (Exception exc)
    {
        return false;
    }
}

2 comments: