adsense

Friday, January 26, 2024

C# download file from a given URL

 If you want to download a file  in C # form a given url following code snippet can be used.

 public static async Task Download(string remoteUri,   string directory)

        {

            try

            {

               

                string filePath = Path.Combine(directory, Path.GetFileName(remoteUri));

                var httpClient = new HttpClient();

                if (!Directory.Exists(directory))

                {

                    Directory.CreateDirectory(directory);

                }

                using var stream = await httpClient.GetStreamAsync(remoteUri);

                using var fileStream = new FileStream(filePath, FileMode.Create);

                 await stream.CopyToAsync(fileStream);


            }

            catch (Exception)

            {

                throw;

            }


        }


 When calling the above method we can user as

Download("https://abc.com/Content/Images/imagename.jpg", Directory.GetCurrentDirectory() + "\\images\\").Wait();

Note that this code is compatible with .Net 6 and .Net 7.

cheers,

Samitha

No comments:

Post a Comment