0
public async Task DownloadFile(string urlAddress, string location)
{
    Stopwatch sw = new Stopwatch();

    using (WebClient webClient = new WebClient())
    {  
        webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0 Chrome");
        webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(((sender, e) => Completed(sender, e, sw)));
        webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => ProgressChanged(sender, e, sw));

        Uri URL = new Uri(urlAddress);

        sw.Start();

        try
        {
            await webClient.DownloadFileTaskAsync(URL, location);
        }
        catch (Exception ex)
        {
            this.Invoke(new Action(() =>
                    {
                        Uri t = URL;
                        string tt = location;
                        MessageBox.Show(ex.ToString());
                    }));
        }
    }
}

When downloading files when it's saving the files on the hard disk some files contains Illegal characters.

For example when it's getting to the catch the variable location content is :

Ghost While They Sleep (FUNNY?).mp4

I think the problem is the ? in the file name or maybe the () too.

How can I solve the file name in these cases?

I don't want to pass this files but maybe somehow to change the name of the file to something legal.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    https://stackoverflow.com/questions/2435894/how-do-i-check-for-illegal-characters-in-a-path – Hans Passant Oct 20 '22 at 20:35
  • 2
    It's not uncommon to simply replace invalid characters with something valid, like an underscore. But if this program has a user interface you may want to just catch this specific type of error and report to the user that the filename was invalid and ask them to choose a new name. – StriplingWarrior Oct 20 '22 at 20:40

0 Answers0