System.Net.WebClient is giving me an error while downloading a file from IIS hosted .NET Core 2.1 application

Viewed 280

I have a file "20181023151311-book + notes.txt" stored in an application hosted in IIS server inside a folder named as "MyFiles" and I have to pull the file in a WPF application. I am using WebClient to download the file from the server but it is giving me an error

The remote server returned an error: (404) Not Found.

I tried to use System.Web.HttpUtitility.UrlEncode but still I am getting an error. Here is the code I used to pull the file from the server. The code runs perfectly if there are no special characters. Could you please help to solve the issue? Thanks!

using System.Windows;

namespace WebClientDownloadDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            DownloadFile(@"https://localhost:40120/MyFiles/20181023151311-book + notes.txt");
        }

        public void DownloadFile(string fileUrl)
        {
            using (var client = new System.Net.WebClient())
            {
                var fileName = fileUrl.Substring(fileUrl.LastIndexOf(@"/") + 1);
                client.DownloadFile(fileUrl, System.IO.Path.Combine("C:\\Users\\Username\\Downloads", fileName));
            }
        }
    }
}
0 Answers
Related