Search code examples
c#stringuploadcoded-ui-testssendkeys

C#: System.Windows.Forms.SendKeys.SendWait does not work with the path as input


Here is my code

private string path = Path.GetTempPath() + "Test.pdf";
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.AllThreads;
System.Windows.Forms.SendKeys.SendWait(path);
Playback.PlaybackSettings.WaitForReadyLevel = WaitForReadyLevel.UIThreadOnly;
Keyboard.SendKeys("{Enter}");

There is a window explorer for opening a file. The file exists on the temp path. It sometimes works and sometimes it enter the path as :\Users\.... which means it ignores C. I am not sure what is the problem? Why it is inconsistent? Any help is appreciated.

I already tried

private string path = @"" + Path.GetTempPath() + "Test.pdf";

but it is the same (sometimes works, sometimes does not)

I added empty char before the path

private string path = @" " + Path.GetTempPath() + "Test.pdf";

But still it is the same!


Solution

  • I had a similar problem with Coded UI but it omitted a small number of characters randomly throughout the string. I never found out the real reason, but I got around the problem by sending the characters one at a time with a short pause between them. I use code similar to the following:

    void SendKeysSlowly(string text)
    {
        foreach ( char s in text )
        {
            SendKeys(s); // Choose the appropriate send routine
            System.Threading.Thread.Sleep(50); // Milliseconds, adjust as needed
        }
    }
    

    Also, you should ensure the string always starts with a "C:"? You could add code of the form Assert(path.StartsWith("C:\\")); before the first ...Sendkeys call.