簡體   English   中英

將客戶端連接到服務器,並在C#中從中獲取文本文件

[英]connect client to server and get a text file from it in C#

我想使用C#中的IP地址自動從客戶端連接到服務器,並從服務器獲取文本文件。

實現此目標的最佳方法是什么?

網絡客戶端

最簡單的方法是使用“ WebClient”。 參見https://msdn.microsoft.com/zh-cn/library/system.net.webclient(v=vs.110).aspx

此類具有一個稱為

public string DownloadString(string address)

您可以使用它來將文本文件下載到內存中。 有關更多方法(例如DownloadFile),請訪問給定的鏈接。 注意:如果在下載內容時在UI線程中執行此方法,則可能會掛起窗口。 使用第二個線程來做這些事情,或者盡可能使用異步方法。

在這種情況下,您寧願使用以下命令:

public Task<string> DownloadStringTaskAsync(string address)

有關異步的更多信息: https ://msdn.microsoft.com/zh-cn/library/dd537609( v= vs.110).aspx

使用WebRequest可以很容易地實現如下。

// Create a request for the URL. 
WebRequest request = WebRequest.Create("http://yourdomain.com/textfile");
// Get the response.
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM