webClient.DownloadFileAsync not working

Bruce Krueger 331 Reputation points
2022-04-03T03:07:52.043+00:00

What am I doing wrong?

   int row = 0;  
           string url = "https://www.gamesbypapa.com/wp-content/uploads/sacbrewclubnames.csv";  
           string cacheDir = FileSystem.CacheDirectory;  
           string fileName = "sacbrewclubnames.csv";  
           string line;  
           string fullPath;  
           readonly string[,] table1 = new string[20, 0]; //rows , columns  
     
           public MainPage()  
           {  
               InitializeComponent();  
               RequestPermissions();  
               string[] paths = { cacheDir, fileName };  
               fullPath = Path.Combine(paths);  
               getFile();  
               FileStream();  
           }  
           async Task RequestPermissions()  
           {  
               var status = await Permissions.CheckStatusAsync<Permissions.StorageWrite>();  
               var status2 = await Permissions.CheckStatusAsync<Permissions.StorageRead>();  
     
               if (status != PermissionStatus.Granted)  
               {  
                   await Permissions.RequestAsync<Permissions.StorageWrite>();  
               }  
               if (status2 != PermissionStatus.Granted)  
               {  
                   await Permissions.RequestAsync<Permissions.StorageRead>();  
               }  
               if (status == PermissionStatus.Granted) Label1.Text = "StorageWrite Granted";  
               if (status == PermissionStatus.Granted) Label2.Text = "StorageRead Granted";  
           }  
           public void getFile()  
           {  
               var pathToNewFolder = cacheDir;  
               Directory.CreateDirectory(pathToNewFolder);  
               try  
               {  
                   WebClient webClient = new WebClient();  
                   webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);  
                   var folder = cacheDir;  
                   webClient.DownloadFileAsync(new Uri("https://www.gamesbypapa.com/wp-content/uploads/sacbrewclubnames.csv"), fullPath);  
                   Label3.Text = fullPath;  
               }  
               catch (Exception ex)  
               {  
                   Label4.Text = "ERROR:" + ex.Message;  
               }  
           }  
     private void Completed(object sender, AsyncCompletedEventArgs e)  
           {  
               Label5.Text = "ERROR: " + e.Error.Message;  
           }  
     
           public async Task FileStream()  
           {  
               //using (var stream = await FileSystem.OpenAppPackageFileAsync(fullPath))  
               //{  
               if (File.Exists(fullPath)) Label6.Text = "File Exists"; else Label6.Text = "File does not exist";  
               using (var sr = new StreamReader(fullPath))  
               {  
                   row = 0;  
                   line = sr.ReadLine();  
                   //while (line != null)  
                   //{  
                   Label7.Text = "7:" + line;  
                   table1[row, 0] = line;  
                   Label8.Text = "8:" + table1[0, 0];  
                   //row++;  
                   //line = sr.ReadLine();  
                   //}  
                   sr.Close();  
                   // }  
               }  
           }  
       }  
   }  

This is the result:

189466-image.png

Certificate on WebPage expires 5/22/2022. You can download the file by using the url.

Developer technologies | .NET | Xamarin
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Anonymous
    2022-04-04T04:05:23.443+00:00

    Hello,

    Based on your error, I find a known issue about it. If PG have any fixes, they will update in this GitHub page.

    Here is a workaround, you can try it, please set return value to true for ServicePointManager.ServerCertificateValidationCallback that determines whether the specified certificate is accepted for authentication like following code in your getFile method .

       WebClient webClient = new WebClient();  
                       webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);   
                       ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback  
                       (  
                           delegate { return true; }  
                       );  
                       var folder = cacheDir;  
                       webClient.DownloadFileAsync(new Uri("https://www.gamesbypapa.com/wp-content/uploads/sacbrewclubnames.csv"), fullPath);  
    

    You put async method in the constructor directly, please do not set it like this way. You can use a static creation method to make a Factory Pattern or use AsyncLazy, please use your favorite browser to search Stephen Cleary's blog about Async Constructors to find more details to fix this issue, I put these method to button click event for testing,

       private async void Button_Clicked(object sender, EventArgs e)  
               {  
                   await  RequestPermissions();  
                   string[] paths = { cacheDir, fileName };  
                   fullPath = Path.Combine(paths);  
                   getFile();          
               }  
    

    I notice you set readonly string[,] table1 = new string[20, 0];, due to readonly property, you cannot set the value like table1[row, 0] = line; code in the FileStream method. Please remove readonly, if you want to set it. If you want to use Multidimensional Arrays, please do not set new string[20, 0], set new string[20, 1]; at least.

    And I invoke FileStream in the Completed(object sender, AsyncCompletedEventArgs e).

    By the way, if you have any errors or exceptions, please share it completely with text, do not post screenshot, it will help us to troubleshot this issue quickly.

    Best Regards,
    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

  2. Bruce Krueger 331 Reputation points
    2022-04-10T01:14:53.79+00:00

    @Anonymous
    I am successful in DownloadFIle and then reading the file.
    I update the Array answer by one and then rewrite the file.
    And then UploadFile.

    But the File on the Web does not change.
    What am I doing wrong?

    public partial class MainPage : ContentPage
    {
    int row = 0;
    int activity;
    int button = 0;
    string url = "https://www.gamesbypapa.com/wp-content/uploads/sacactivity.txt";
    string cacheDir = FileSystem.CacheDirectory;
    string fileName = "sacactivity.txt";
    string line;
    string fullPath;
    string[,] table1 = new string[20, 1]; //rows , columns

        public MainPage()  
        {  
            InitializeComponent();  
    
        }  
        private async void Button1_Clicked(object sender, EventArgs e)  
        {  
            await RequestPermissions();  
            string[] paths = { cacheDir, fileName };  
            fullPath = Path.Combine(paths);  
            GetFile();  
            Label3.Text = "GetFile";  
            button = 1;  
        }  
        private async void Button2_Clicked(object sender, EventArgs e)  
        {  
            if (button == 0)  
            {  
                await RequestPermissions();  
                string[] paths = { cacheDir, fileName };  
                fullPath = Path.Combine(paths);  
            }  
            await ReadLocal();  
            activity = Int16.Parse(table1[0, 0]);  
            activity++;  
            table1[0, 0] = activity.ToString();  
            Label4.Text = table1[0, 0];  
            Label5.Text = "ReadLocal";  
        }  
        private async void Button3_Clicked(object sender, EventArgs e)  
        {  
    
            await WriteLocal();  
            Label6.Text = table1[0, 0];  
            Label7.Text = "WriteLocal";  
        }  
        private async void Button4_Clicked(object sender, EventArgs e)  
        {  
    
            WriteWebFile();  
            Label8.Text = table1[0, 0];  
            Label9.Text = "WriteWebFile";  
        }  
    
        async Task RequestPermissions()  
        {  
            var status = await Permissions.CheckStatusAsync<Permissions.StorageWrite>();  
            var status2 = await Permissions.CheckStatusAsync<Permissions.StorageRead>();  
    
            if (status != PermissionStatus.Granted)  
            {  
                await Permissions.RequestAsync<Permissions.StorageWrite>();  
            }  
            if (status2 != PermissionStatus.Granted)  
            {  
                await Permissions.RequestAsync<Permissions.StorageRead>();  
            }  
        }  
        public void GetFile()  
        {  
            var pathToNewFolder = cacheDir;  
            Directory.CreateDirectory(pathToNewFolder);  
            WebClient webClient = new WebClient();  
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });  
            var folder = cacheDir;  
            webClient.DownloadFile(new Uri(url), fullPath);  
        }  
    
        public async Task ReadLocal()  
        {  
            try  
            {  
                using (var sr = new StreamReader(fullPath))  
                {  
                    line = sr.ReadLine();  
                    row = 0;  
                    while (line != null)  
                    {  
                        table1[row, 0] = line;  
                        row++;  
                        line = sr.ReadLine();  
                    }  
                    Label1.Text = table1[0, 0];  
                    Label2.Text = table1[1, 0];  
                    sr.Close();  
                }  
            }  
            catch (Exception ex) { Label1.Text = "Error: " + ex.Message; }  
        }  
        public void WriteWebFile()  
        {  
            try  
            {  
                var pathToNewFolder = cacheDir;  
                WebClient webClient = new WebClient();  
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });  
                var folder = cacheDir;  
                webClient.UploadFile(new Uri(url), fullPath);  
            }  
            catch (Exception ex) { Label1.Text = "Error: " + ex.Message; }  
    
        }  
        public async Task WriteLocal()  
        {  
    
            StreamWriter sw = new StreamWriter(fullPath, true);  
            row = 0;  
            while (table1[row, 0] != null)  
            {  
                line = table1[row, 0];  
                row++;  
                sw.WriteLine(line);  
            }  
            sw.Close();  
        }  
    }  
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.