简体   繁体   English

将客户端连接到服务器,并在C#中从中获取文本文件

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

I would like to connect automatically from a client to a server with an IP address in C# and get a text file from the server. 我想使用C#中的IP地址自动从客户端连接到服务器,并从服务器获取文本文件。

What would be the best way to achieve this ? 实现此目标的最佳方法是什么?

WebClient 网络客户端

The simplest way to do so is using "WebClient". 最简单的方法是使用“ WebClient”。 See https://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.110).aspx 参见https://msdn.microsoft.com/zh-cn/library/system.net.webclient(v=vs.110).aspx

This class has a function called 此类具有一个称为

public string DownloadString(string address)

You can use this to download the text file to memory. 您可以使用它来将文本文件下载到内存中。 For more Methods (eg DownloadFile) visit the given link. 有关更多方法(例如DownloadFile),请访问给定的链接。 Note: This Method might hang the window if executed in the UI-Thread while downloading the content. 注意:如果在下载内容时在UI线程中执行此方法,则可能会挂起窗口。 Either use a second Thread to do the stuff or use the asynchronous methods if possible. 使用第二个线程来做这些事情,或者尽可能使用异步方法。

In this case you would rather use this: 在这种情况下,您宁愿使用以下命令:

public Task<string> DownloadStringTaskAsync(string address)

More Information about Async: https://msdn.microsoft.com/en-us/library/dd537609(v=vs.110).aspx 有关异步的更多信息: https ://msdn.microsoft.com/zh-cn/library/dd537609( v= vs.110).aspx

It is easy to achieve using a WebRequest as follows. 使用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