Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.WaitForFileChooserAsync
ScheduleController.cs
Source:ScheduleController.cs  
...384                                var html2 = await page.GetContentAsync();385                                if (html2.Contains("Welcome to Instagram"))386                                {387                                    page.EvaluateExpressionAsync(@"document.querySelector(""header button"").click()");388                                    var fileChooser = await page.WaitForFileChooserAsync();389                                    await fileChooser.AcceptAsync(new string[] { HostingEnvironment.MapPath(schedule.ImagePath) });390                                    await PageNavigation(page);391                                }392                                else393                                {394                                    try395                                    {396                                        page.EvaluateExpressionAsync(ClickButton("Your Story"));397                                        var fileChooser = await page.WaitForFileChooserAsync();398                                        await fileChooser.AcceptAsync(new string[] { HostingEnvironment.MapPath(schedule.ImagePath) });399                                        await PageNavigation(page);400                                    }401                                    catch (Exception ex)402                                    {403                                        page.EvaluateExpressionAsync(ClickButton("Not Now"));404                                        var fileChooser = await page.WaitForFileChooserAsync();405                                        await fileChooser.AcceptAsync(new string[] { HostingEnvironment.MapPath(schedule.ImagePath) });406                                        await PageNavigation(page);407                                    }408                                }409                                try410                                {411                                    System.Threading.Thread.Sleep(5000);412                                    await page.EvaluateExpressionAsync(ClickButton("Add to your story"));413                                    System.Threading.Thread.Sleep(500);414                                    await PageNavigation(page);415                                    System.Threading.Thread.Sleep(5000);416                                    schedule.PostedStatus = true;417                                    schedule.LastTryDate = DateTime.Now;418                                    schedule.Exception = "";419                                }420                                catch (Exception ex)421                                {422                                    schedule.PostedStatus = true;423                                    schedule.LastTryDate = DateTime.Now;424                                    schedule.Exception = "Story Already Posted";425                                }426                            }427                            else428                            {429                                page.EvaluateExpressionAsync(@"document.querySelector(""div[data-testid=new-post-button]"").click()");430                                var fileChooser = await page.WaitForFileChooserAsync();431                                await fileChooser.AcceptAsync(new string[] { HostingEnvironment.MapPath(schedule.ImagePath) });432                                await PageNavigation(page);433                                System.Threading.Thread.Sleep(5000);434                                await page.EvaluateExpressionAsync(ClickButton("Next"));435                                await PageNavigation(page);436                                System.Threading.Thread.Sleep(5000);437                                for (int i = 0; i < 4; i++)438                                {439                                    await page.Keyboard.DownAsync(key: "Tab");440                                    System.Threading.Thread.Sleep(500);441                                }442                                await page.Keyboard.TypeAsync(schedule.Caption, new TypeOptions { Delay = 200 });443                                await page.EvaluateExpressionAsync(ClickButton("Share"));444                                System.Threading.Thread.Sleep(500);...FileChooserAcceptTests.cs
Source:FileChooserAcceptTests.cs  
...14        [Fact]15        public async Task ShouldWorkWhenFileInputIsAttachedToDOM()16        {17            await Page.SetContentAsync("<input type=file>");18            var waitForTask = Page.WaitForFileChooserAsync();19            await Task.WhenAll(20                waitForTask,21                Page.ClickAsync("input"));22            Assert.NotNull(waitForTask.Result);23        }24        [Fact]25        public async Task ShouldAcceptSingleFile()26        {27            await Page.SetContentAsync("<input type=file oninput='javascript:console.timeStamp()'>");28            var waitForTask = Page.WaitForFileChooserAsync();29            var metricsTcs = new TaskCompletionSource<bool>();30            await Task.WhenAll(31                waitForTask,32                Page.ClickAsync("input"));33            Page.Metrics += (sender, e) => metricsTcs.TrySetResult(true);34            await Task.WhenAll(35                waitForTask.Result.AcceptAsync(TestConstants.FileToUpload),36                metricsTcs.Task);37            Assert.Equal(1, await Page.QuerySelectorAsync("input").EvaluateFunctionAsync<int>("input => input.files.length"));38            Assert.Equal(39                "file-to-upload.txt",40                await Page.QuerySelectorAsync("input").EvaluateFunctionAsync<string>("input => input.files[0].name"));41        }42        [Fact]43        public async Task ShouldBeAbleToReadSelectedFile()44        {45            await Page.SetContentAsync("<input type=file>");46            _ = Page.WaitForFileChooserAsync().ContinueWith(t => t.Result.AcceptAsync(TestConstants.FileToUpload));47            Assert.Equal(48                "contents of the file",49                await Page.QuerySelectorAsync("input").EvaluateFunctionAsync<string>(@"async picker =>50                {51                    picker.click();52                    await new Promise(x => picker.oninput = x);53                    const reader = new FileReader();54                    const promise = new Promise(fulfill => reader.onload = fulfill);55                    reader.readAsText(picker.files[0]);56                    return promise.then(() => reader.result);57                }"));58        }59        [Fact]60        public async Task ShouldBeAbleToResetSelectedFilesWithEmptyFileList()61        {62            await Page.SetContentAsync("<input type=file>");63            _ = Page.WaitForFileChooserAsync().ContinueWith(t => t.Result.AcceptAsync(TestConstants.FileToUpload));64            Assert.Equal(65                1,66                await Page.QuerySelectorAsync("input").EvaluateFunctionAsync<int>(@"async picker =>67                {68                picker.click();69                await new Promise(x => picker.oninput = x);70                return picker.files.length;71            }"));72            _ = Page.WaitForFileChooserAsync().ContinueWith(t => t.Result.AcceptAsync());73            Assert.Equal(74                0,75                await Page.QuerySelectorAsync("input").EvaluateFunctionAsync<int>(@"async picker =>76                {77                picker.click();78                await new Promise(x => picker.oninput = x);79                return picker.files.length;80            }"));81        }82        [Fact]83        public async Task ShouldNotAcceptMultipleFilesForSingleFileInput()84        {85            await Page.SetContentAsync("<input type=file>");86            var waitForTask = Page.WaitForFileChooserAsync();87            await Task.WhenAll(88                waitForTask,89                Page.ClickAsync("input"));90            var ex = await Assert.ThrowsAsync<MessageException>(() => waitForTask.Result.AcceptAsync(91                "./assets/file-to-upload.txt",92                "./assets/pptr.png"));93        }94        [Fact]95        public async Task ShouldFailWhenAcceptingFileChooserTwice()96        {97            await Page.SetContentAsync("<input type=file>");98            var waitForTask = Page.WaitForFileChooserAsync();99            await Task.WhenAll(100                waitForTask,101                Page.ClickAsync("input"));102            var fileChooser = waitForTask.Result;103            await fileChooser.AcceptAsync();104            var ex = await Assert.ThrowsAsync<PuppeteerException>(() => waitForTask.Result.AcceptAsync());105            Assert.Equal("Cannot accept FileChooser which is already handled!", ex.Message);106        }107    }108}...ContaJaNFeNotifier.cs
Source:ContaJaNFeNotifier.cs  
...57                await page.SelectAsync("select[name=\"tipo\"]", "2");58                //Defines the invoice description59                await page.TypeAsync("textarea[name=\"descricao\"]", confs.NFDescription);60                //Clicks the upload file button and waits for the file picker to show up61                var fileChooserTask = page.WaitForFileChooserAsync();62                await Task.WhenAll(fileChooserTask, page.ClickAsync("input[name=\"documento\"]"));63                //Choses the XML file created earlier and confirms64                await fileChooserTask.Result.AcceptAsync(xmlFile.FullName);65                //Clicks the submit button and waits for the page to refresh66                await Task.WhenAll(67                    page.ClickAsync("button[type=\"submit\"]"),68                    page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.DOMContentLoaded } }));69            }70            finally71            {72                //Disposes of the temporary file created73                xmlFile.Directory.Delete(recursive: true);74            }75        }...PageWaitForFileChooserTests.cs
Source:PageWaitForFileChooserTests.cs  
...14        [Fact]15        public async Task ShouldWorkWhenFileInputIsAttachedToDOM()16        {17            await Page.SetContentAsync("<input type=file>");18            var waitForTask = Page.WaitForFileChooserAsync();19            await Task.WhenAll(20                waitForTask,21                Page.ClickAsync("input"));22            Assert.NotNull(waitForTask.Result);23        }24        [Fact]25        public async Task ShouldWorkWhenFileInputIsNotAttachedToDOM()26        {27            var waitForTask = Page.WaitForFileChooserAsync();28            await Task.WhenAll(29                waitForTask,30                Page.EvaluateFunctionAsync(@"() =>31                {32                    const el = document.createElement('input');33                    el.type = 'file';34                    el.click();35                }"));36            Assert.NotNull(waitForTask.Result);37        }38        [Fact]39        public async Task ShouldRespectTimeout()40        {41            var ex = await Assert.ThrowsAsync<TimeoutException>(() => Page.WaitForFileChooserAsync(new WaitForFileChooserOptions42            {43                Timeout = 144            }));45        }46        [Fact]47        public async Task ShouldRespectTimeoutWhenThereIsNoCustomTimeout()48        {49            Page.DefaultTimeout = 1;50            var ex = await Assert.ThrowsAsync<TimeoutException>(() => Page.WaitForFileChooserAsync());51        }52        [Fact]53        public async Task ShouldPrioritizeExactTimeoutOverDefaultTimeout()54        {55            Page.DefaultTimeout = 0;56            var ex = await Assert.ThrowsAsync<TimeoutException>(() => Page.WaitForFileChooserAsync(new WaitForFileChooserOptions57            {58                Timeout = 159            }));60        }61        [Fact]62        public async Task ShouldWorkWithNoTimeout()63        {64            var waitForTask = Page.WaitForFileChooserAsync(new WaitForFileChooserOptions { Timeout = 0 });65            await Task.WhenAll(66                waitForTask,67                Page.EvaluateFunctionAsync(@"() => setTimeout(() =>68                {69                    const el = document.createElement('input');70                    el.type = 'file';71                    el.click();72                }, 50)"));73            Assert.NotNull(waitForTask.Result);74        }75        [Fact]76        public async Task ShouldReturnTheSameFileChooserWhenThereAreManyWatchdogsSimultaneously()77        {78            await Page.SetContentAsync("<input type=file>");79            var fileChooserTask1 = Page.WaitForFileChooserAsync();80            var fileChooserTask2 = Page.WaitForFileChooserAsync();81            await Task.WhenAll(82                fileChooserTask1,83                fileChooserTask2,84                Page.QuerySelectorAsync("input").EvaluateFunctionAsync("input => input.click()"));85            Assert.Same(fileChooserTask1.Result, fileChooserTask2.Result);86        }87    }88}...FileChooser.cs
Source:FileChooser.cs  
...5using PuppeteerSharp.Messaging;6namespace PuppeteerSharp7{8    /// <summary>9    /// <see cref="FileChooser"/> objects are returned via the <seealso cref="Page.WaitForFileChooserAsync(WaitForFileChooserOptions)"/> method.10    /// File choosers let you react to the page requesting for a file.11    /// </summary>12    /// <example>13    /// <code>14    /// <![CDATA[15    /// var waitTask = page.WaitForFileChooserAsync();16    /// await Task.WhenAll(17    ///     waitTask,18    ///     page.ClickAsync("#upload-file-button")); // some button that triggers file selection19    /// 20    /// await waitTask.Result.AcceptAsync('/tmp/myfile.pdf');21    /// ]]>22    /// </code>23    /// </example>24    /// <remarks>25    /// In browsers, only one file chooser can be opened at a time.26    /// All file choosers must be accepted or canceled. Not doing so will prevent subsequent file choosers from appearing.27    /// </remarks>28    public class FileChooser29    {...FileChooserCancelTests.cs
Source:FileChooserCancelTests.cs  
...17            // Consider file chooser canceled if we can summon another one.18            // There's no reliable way in WebPlatform to see that FileChooser was19            // canceled.20            await Page.SetContentAsync("<input type=file>");21            var waitForTask = Page.WaitForFileChooserAsync();22            await Task.WhenAll(23                waitForTask,24                Page.ClickAsync("input"));25            var fileChooser = waitForTask.Result;26            await fileChooser.CancelAsync();27            await Task.WhenAll(28                Page.WaitForFileChooserAsync(),29                Page.ClickAsync("input"));30        }31        [Fact]32        public async Task ShouldFailWhenCancelingFileChooserTwice()33        {34            await Page.SetContentAsync("<input type=file>");35            var waitForTask = Page.WaitForFileChooserAsync();36            await Task.WhenAll(37                waitForTask,38                Page.ClickAsync("input"));39            var fileChooser = waitForTask.Result;40            await fileChooser.CancelAsync();41            var ex = await Assert.ThrowsAsync<PuppeteerException>(() => fileChooser.CancelAsync());42            Assert.Equal("Cannot accept FileChooser which is already handled!", ex.Message);43        }44    }45}...FileChooserIsMultipleTests.cs
Source:FileChooserIsMultipleTests.cs  
...14        [Fact]15        public async Task ShouldWorkForSingleFilePick()16        {17            await Page.SetContentAsync("<input type=file>");18            var waitForTask = Page.WaitForFileChooserAsync();19            await Task.WhenAll(20                waitForTask,21                Page.ClickAsync("input"));22            Assert.False(waitForTask.Result.IsMultiple);23        }24        [Fact]25        public async Task ShouldWorkForMultiple()26        {27            await Page.SetContentAsync("<input type=file multiple>");28            var waitForTask = Page.WaitForFileChooserAsync();29            await Task.WhenAll(30                waitForTask,31                Page.ClickAsync("input"));32            Assert.True(waitForTask.Result.IsMultiple);33        }34        35        [Fact]36        public async Task ShouldWorkForWebkitDirectory()37        {38            await Page.SetContentAsync("<input type=file multiple webkitdirectory>");39            var waitForTask = Page.WaitForFileChooserAsync();40            await Task.WhenAll(41                waitForTask,42                Page.ClickAsync("input"));43            Assert.True(waitForTask.Result.IsMultiple);44        }45    }46}...WaitForFileChooserOptions.cs
Source:WaitForFileChooserOptions.cs  
2{3    /// <summary>4    /// Optional waiting parameters.5    /// </summary>6    /// <seealso cref="Page.WaitForFileChooserAsync(WaitForFileChooserOptions)"/>7    public class WaitForFileChooserOptions8    {9        /// <summary>10        /// Maximum time to wait for in milliseconds. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.11        /// The default value can be changed by setting the <see cref="Page.DefaultTimeout"/> property.12        /// </summary>13        public int Timeout { get; set; } = Puppeteer.DefaultTimeout;14    }...WaitForFileChooserAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static async Task Main(string[] args)7        {8            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9            var browser = await Puppeteer.LaunchAsync(new LaunchOptions10            {11            });12            var page = await browser.NewPageAsync();13            await page.SetRequestInterceptionAsync(true);14            page.Request += async (sender, e) =>15            {16                if (e.Request.ResourceType == ResourceType.Image)17                {18                    await e.Request.AbortAsync();19                }20                {21                    await e.Request.ContinueAsync();22                }23            };24            await page.WaitForFileChooserAsync();25            await page.ClickAsync("input[type='file']");26            await page.Keyboard.TypeAsync(@"C:\Users\testuser\testfile.txt");27            await page.Keyboard.PressAsync("Enter");28            await browser.CloseAsync();29        }30    }31}WaitForFileChooserAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static async Task Main(string[] args)7        {8            {9            };10            using (var browser = await Puppeteer.LaunchAsync(options))11            using (var page = await browser.NewPageAsync())12            {13                await page.WaitForSelectorAsync("iframe");14                var frames = page.Frames;15                var frame = frames[1];16                var elementHandle = await frame.WaitForSelectorAsync("input[type=file]");17                await elementHandle.UploadFileAsync(@"C:\Users\1.txt");18                await page.WaitForSelectorAsync("input[type=submit]");19                var submit = await page.QuerySelectorAsync("input[type=submit]");20                await submit.ClickAsync();21            }22        }23    }24}25using System;26using System.Threading.Tasks;27using PuppeteerSharp;28{29    {30        static async Task Main(string[] args)31        {32            {33            };34            using (var browser = await Puppeteer.LaunchAsync(options))35            using (var page = await browser.NewPageAsync())36            {37                await page.WaitForSelectorAsync("iframe");38                var frames = page.Frames;39                var frame = frames[1];40                await page.SetFileChooserInterceptedAsync(true);41                var elementHandle = await frame.WaitForSelectorAsync("input[type=file]");42                await elementHandle.ClickAsync();43                var fileChooser = await page.WaitForFileChooserAsync();44                await fileChooser.SetFilesAsync(@"C:\Users\1.txt");45                await page.SetFileChooserInterceptedAsync(false);46                await page.WaitForSelectorAsync("input[type=submit]");47                var submit = await page.QuerySelectorAsync("input[type=submit]");48                await submit.ClickAsync();49            }50        }51    }52}WaitForFileChooserAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static void Main(string[] args)7        {8            MainAsync().GetAwaiter().GetResult();9        }10        static async Task MainAsync()11        {12            var browser = await Puppeteer.LaunchAsync(new LaunchOptions13            {14            });15            var page = await browser.NewPageAsync();16            var task = page.WaitForFileChooserAsync();17            await page.ClickAsync("input[type=file]");WaitForFileChooserAsync
Using AI Code Generation
1using System;2using System.IO;3using System.Threading.Tasks;4using PuppeteerSharp;5{6    {7        static void Main(string[] args)8        {9            MainAsync().Wait();10        }11        static async Task MainAsync()12        {13            {14                ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"15            };16            using (var browser = await Puppeteer.LaunchAsync(options))17            {18                var page = await browser.NewPageAsync();19                var input = await page.QuerySelectorAsync("input[type=file]");20                var fileChooser = await page.WaitForFileChooserAsync();21                await fileChooser.SetFilesAsync(@"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg");22                await input.ClickAsync();23            }24        }25    }26}27using System;28using System.IO;29using System.Threading.Tasks;30using PuppeteerSharp;31{32    {33        static void Main(string[] args)34        {35            MainAsync().Wait();36        }37        static async Task MainAsync()38        {39            {40                ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"41            };42            using (var browser = await Puppeteer.LaunchAsync(options))43            {44                var page = await browser.NewPageAsync();45                var input = await page.QuerySelectorAsync("input[type=file]");WaitForFileChooserAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5	{6		static async Task Main(string[] args)7		{8			{9			};10			var browser = await Puppeteer.LaunchAsync(options);11			var page = await browser.NewPageAsync();12			await page.SwitchToFrameAsync("iframeResult");13			var fileChooser = await page.WaitForFileChooserAsync();14			await fileChooser.SetFilesAsync(@"C:\Users\username\Desktop\test.txt");15			await page.ClickAsync("#btnSubmit");16		}17	}18}WaitForFileChooserAsync
Using AI Code Generation
1var page = await browser.NewPageAsync();2await page.WaitForFileChooserAsync();3await page.ClickAsync("input[type=file]");4var page = await browser.NewPageAsync();5await page.WaitForFileChooserAsync();6await page.ClickAsync("input[type=file]");7var page = await browser.NewPageAsync();8await page.WaitForFileChooserAsync();9await page.ClickAsync("input[type=file]");10var page = await browser.NewPageAsync();11await page.WaitForFileChooserAsync();12await page.ClickAsync("input[type=file]");13var page = await browser.NewPageAsync();14await page.WaitForFileChooserAsync();15await page.ClickAsync("input[type=file]");16var page = await browser.NewPageAsync();17await page.WaitForFileChooserAsync();18await page.ClickAsync("input[type=file]");19var page = await browser.NewPageAsync();20await page.WaitForFileChooserAsync();21await page.ClickAsync("input[type=file]");22var page = await browser.NewPageAsync();23await page.WaitForFileChooserAsync();24await page.ClickAsync("input[type=file]");25var page = await browser.NewPageAsync();WaitForFileChooserAsync
Using AI Code Generation
1using System;2using System.Threading.Tasks;3using PuppeteerSharp;4{5    {6        static async Task Main(string[] args)7        {8            await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);9            var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false });10            var page = await browser.NewPageAsync();11            await page.ClickAsync("input#id-open-date-picker");12            var fileChooser = await page.WaitForFileChooserAsync();13            await fileChooser.SetFilesAsync(@"C:\Users\username\Documents\file1.txt");14            await page.ClickAsync("button#id-accept-date");15            await page.WaitForSelectorAsync("div#id-date-picker-desc");16            Console.WriteLine("File selected");17            Console.ReadLine();18        }19    }20}Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
