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

Sunday, January 14, 2024

C # get file MIMETYPE

 If we want to determine the mime type of a given file, we can use the MimeTypeMap NuGet package. I found it very efficient and up to date with additions from many contributors.


Cheers,

Samitha