YouTube Video Downloader using C# Console Application

The provided code demonstrates a simple console application that performs a multiple video download process from Youtube.

Step 1. Create a new C# console application project. In Visual Studio, you can follow these steps.

  • Open Visual Studio.
  • Select "Create a new project" or go to "File" > "New" > "Project."
  • Choose "Console App (.NET)" as the project template.
    youTube Video Downloader using C# Console Application
  • Enter a name for your project (e.g., "DownloadYoutubeVideo") and Choose a location to save the project.
    youTube Video Downloader using C# Console Application
  • Select Framework and Click on Next.
    youTube Video Downloader using C# Console Application
  • Click "Create" to create the project.

Use the below code in Program.cs and replace all to Download Video from Youtube.

using YoutubeExplode;

namespace YouTubeDownloader
{
    class Program
    {
        static async Task Main(string[] args)
        {
            // Set the output directory path here
            string outputDirectory = @"D:\YouTubeVideo";

            // List of YouTube video URLs to download
            List<string> videoUrls = new List<string>
            {

                "https://www.youtube.com/watch?v=YT8rY_o5VhY&ab_channel=ZeeMusicCompany",
                "https://www.youtube.com/watch?v=HFX6AZ5bDDo&ab_channel=ZeeMusicCompany",
                // Add more video URLs as needed
            };
            try
            {
                foreach (var videoUrl in videoUrls)
                {
                    await DownloadYouTubeVideo(videoUrl, outputDirectory);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred while downloading the videos: " + ex.Message);
            }
        }
        static async Task DownloadYouTubeVideo(string videoUrl, string outputDirectory)
        {
            var youtube = new YoutubeClient();
            var video = await youtube.Videos.GetAsync(videoUrl);

            // Sanitize the video title to remove invalid characters from the file name
            string sanitizedTitle = string.Join("_", video.Title.Split(Path.GetInvalidFileNameChars()));

            // Get all available muxed streams
            var streamManifest = await youtube.Videos.Streams.GetManifestAsync(video.Id);
            var muxedStreams = streamManifest.GetMuxedStreams().OrderByDescending(s => s.VideoQuality).ToList();

            if (muxedStreams.Any())
            {
                var streamInfo = muxedStreams.First();
                using var httpClient = new HttpClient();
                var stream = await httpClient.GetStreamAsync(streamInfo.Url);
                var datetime = DateTime.Now;

                string outputFilePath = Path.Combine(outputDirectory, $"{sanitizedTitle}.{streamInfo.Container}");
                using var outputStream = File.Create(outputFilePath);
                await stream.CopyToAsync(outputStream);

                Console.WriteLine("Download completed!");
                Console.WriteLine($"Video saved as: {outputFilePath}{datetime}");
            }
            else
            {
                Console.WriteLine($"No suitable video stream found for {video.Title}.");
            }
        }
    }
}

Downloading and Installing NuGet Packages YoutubeExplode.

youTube Video Downloader using C# Console Application

To test the code, follow these steps,

Step 1. Set Output Directory

Set the outputDirectory variable to the directory where you want to save the downloaded YouTube videos. In the provided code, it is set to @"D:\YouTubeVideo", but you can change it to any desired directory on your system.

Step 2. Add Video URLs

Add the YouTube video URLs you want to download to the videoUrls list. In the provided code, two sample video URLs are already added, but you can add more video URLs if needed. Make sure each URL is a valid YouTube video URL.

Step 3. Build and Run the Application

Once you have set the output directory and added the video URLs, build and run the C# console application. The application will start downloading the videos one by one and save them in the specified output directory.

Step 4. Observe the Download Progress

As the application runs, it will display messages indicating the progress. It will show whether the download was completed successfully or if any issues occurred during the download process.

Step 5. Verify Downloaded Videos

After the application completes, navigate to the output directory (e.g., D:\YouTubeVideo in the provided code) on your system. You should find the downloaded YouTube videos saved as individual files with sanitized titles, along with their respective file extensions (e.g., .mp4).

Note. Keep in mind that downloading copyrighted content without the copyright holder's permission may violate YouTube's terms of service and copyright laws. Ensure that you have the necessary rights to download and use the videos you intend to download.

Please test the code responsibly and only use it for videos that you have the right to download or use. The code provided is based on the YoutubeExplode library and might require updates if the library or YouTube's API undergoes any changes.

The YoutubeExplode library interacts with YouTube's public API, and if the video's download option is disabled, the API will not provide the necessary data to fetch the video stream. Therefore, the download won't be possible through this method.

Thank you for reading, and I hope this post has helped provide you with a better understanding of How to download Videos from Youtube Using the YoutubeExplode library. 

"Keep coding, keep innovating, and keep pushing the boundaries of what's possible!

Happy Coding !!!


Similar Articles