如何使用EditText字段(明文)的输入在服务器上编写/创建文本文件?

问题描述 投票:1回答:1

所以我有从服务器读取的功能:

        btnRead.Click += (sender, e) =>
        {
            showtxt.Text = ShowRemoteStringFile("ftp://url/text.txt");
        };

    string ShowRemoteStringFile(string readUrl)
    {
        WebRequest req = WebRequest.Create(readUrl);
        req.Credentials = new NetworkCredential("username", "password");
        WebResponse rsp = (WebResponse)req.GetResponse();
        StreamReader rdr = new StreamReader(rsp.GetResponseStream());
        string result = rdr.ReadToEnd();
        return result;
    }

现在我正在寻找写入功能,但找不到任何东西..我试图将Web请求与SteamWriter连接,但它是一团糟。

我想我必须使用一种完全不同于read函数的方法。谁能在那里分享他的C#,Xamarin天才?提前致谢。

c# android xamarin xamarin.android ftpwebrequest
1个回答
1
投票

您可以使用System.Net库来进行网络连接。你也不是这样做的异步。您应该使按钮功能异步,如下所示。只需将编辑框的内容放在字符串内容字符串中即可。如果您有其他问题,请告诉我。我也包括使用语句。你可以在nuget上获得system.http。

https://www.nuget.org/packages/Microsoft.Net.Http/

using System;
using System.Text;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

async Task<string> ShowRemoteStringFile(string readUrl){

HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                Convert.ToBase64String(
                    System.Text.ASCIIEncoding.ASCII.GetBytes(
                        string.Format("{0}:{1}", Username, Password))));
httpClient.DefaultRequestHeaders.Add("Accept", "text/plain; charset=UTF-8");
var body = new StringContent("your http post body text", Encoding.UTF8, "application/json");
Task<System.Net.Http.HttpResponseMessage> r = httpClient.PostAsync("YOUR_URL", body);
// do stuff while waiting for response to come back
var response = await r; //await the request to return a result from the server 
var responseContent = response.Content;
if (response.IsSuccessStatusCode){
//Do stuff with the response content
}

}

现在让你的按钮异步,这样你就可以在按钮事件中等待:

btnRead.Click += async (sender, e) => 
{
    await ShowRemoteStringFile("string"); 
};

如果您有任何问题,请告诉我:)

© www.soinside.com 2019 - 2024. All rights reserved.