Unable to Write Local or Copy Local file to Web

Bruce Krueger 331 Reputation points
2022-04-15T19:02:13.76+00:00

I have a WebFile that I am successful in using WebClient.DownloadFile in order to load the file on the phone.
I then read the File on the phone into an array and display it.
I then want to make some changes to the array, write the file on the phone over the existing one, and WebClient.UploadFIle to replace the original WebFile.
Something is not working and I am unable to determine what.

using System;
using System.Threading.Tasks;
using System.Net;
using System.Net.Security;
using System.IO;

using Xamarin.Forms;
using Xamarin.Essentials;

namespace ReadWebFile
{

    public partial class MainPage : ContentPage
    {
        int row = 0;
        int step = 0;
        int activity;
        int activity1;
        string url = "https://www.gamesbypapa.com/wp-content/uploads/sacactivity.csv";
        string cacheDir = FileSystem.CacheDirectory;
        string fileName = "sacactivity.csv";
        string line;
        string fullPath;
        string paths;
        string[,] table1 = new string[50,3]; //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();
            Label1.Text = "GetFile";
        }
        private async void Button2_Clicked(object sender, EventArgs e)
        {
            await ReadLocal();
            Label1.Text = table1[0, 0];
            Label2.Text = table1[0, 1];
            Label3.Text = table1[1, 0];
            Label4.Text = table1[1, 1];
            activity = Int16.Parse(table1[0,1]);
            activity++;
            table1[0, 1] = activity.ToString();
            activity1 = Int16.Parse(table1[1,1]);
            activity1++;
            table1[1, 1] = activity1.ToString();
            Label5.Text = table1[0, 0];
            Label6.Text = table1[0, 1];
            Label7.Text = table1[1, 0];
            Label8.Text = table1[1, 1];

        }
        private async void Button3_Clicked(object sender, EventArgs e)
        { 
            await WriteLocal();
            Label9.Text = "WriteLocal";
            Label10.Text = table1[0, 0];
            Label11.Text = table1[0, 1];
            Label12.Text = table1[1, 0];
            Label13.Text = table1[1, 1];
        }
        private async void Button4_Clicked(object sender, EventArgs e)
        {

            WriteWebFile();
            Label14.Text = "WriteWebFile";
            Label15.Text = table1[0,0];
            Label16.Text = table1[0, 1];
            Label17.Text = table1[1, 0];
            Label18.Text = table1[1, 1];
        }

        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()
        {
            using (var sr = new StreamReader(fullPath))
            {
                line = sr.ReadLine();
                row = 0;
                step = 0;
                while (line != null)
                {
                    if (step == 0) { table1[row, 0] = line; line = sr.ReadLine();}
                    if (step == 1) { table1[row, 1] = line; line = sr.ReadLine(); row++; }
                    if (step == 0) { step = 1; } else if (step == 1) { step = 0; }
                }
                sr.Close();
            }
        }
        public async Task WriteLocal()
        {
            try
            {
                StreamWriter sw = new StreamWriter(fullPath, true);
                row = 0;
                while (table1[row, 0] != null)
                {
                    line = table1[row, 0];
                    sw.WriteLine(line);
                    line = table1[row, 1];
                    sw.WriteLine(line);
                    row++;
                }
                sw.Close();
            }
            catch (Exception ex) { Label3.Text = "Error: " + ex.Message; }
        }
        public void WriteWebFile()
        {
            try
            {
                var pathToNewFolder = cacheDir;
                WebClient webClient = new WebClient();
                webClient.UploadFileCompleted += new UploadFileCompletedEventHandler(Completed);
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
                var folder = cacheDir;
                webClient.UploadFile(new Uri(url), fullPath);
            }
            catch (Exception ex) { Label3.Text = "Error: " + ex.Message; }

        }
        private void Completed(object sender, UploadFileCompletedEventArgs e)
        {
            Label4.Text = "Completed ERROR: " + e.Error.Message;
        }

        private void WebClient_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
        {
            Label5.Text = "NotImplementedException";
            throw new NotImplementedException();

        }
    }
}
Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,301 questions
0 comments No comments
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 36,951 Reputation points Microsoft Vendor
    2022-04-18T05:26:43.077+00:00

    Hello,

    The WebClient.UploadFile Method uploads the data, then you need server-side code to save the file.

    In the official documentation WebClient.UploadFile Method, you can find the following remark.

    The POST method is defined by HTTP. If the underlying request does not use HTTP and POST is not understood by the server, the underlying protocol classes determine what occurs.

    In addition, StreamWriter sw = new StreamWriter(fullPath, true); this code in your WriteLocal function will cause the out of range error if you run ReadLocal -> WriteLocal -> ReadLocal.

    It's caused by the true value. True means to append content to the file. You need to set false for StreamWriter to overwrite your file to avoid out of range error.

    You can refer to this documentation: https://learn.microsoft.com/en-us/dotnet/api/system.io.streamwriter.-ctor?view=net-6.0#system-io-streamwriter-ctor(system-string-system-boolean) .

    Best Regards,

    Alec Liu.


    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.


0 additional answers

Sort by: Most helpful