简体   繁体   中英

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.

What would be the best way to achieve this ?

WebClient

The simplest way to do so is using "WebClient". See https://msdn.microsoft.com/en-us/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. Note: This Method might hang the window if executed in the UI-Thread while downloading the content. 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

It is easy to achieve using a WebRequest as follows.

// 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM