простой вопрос: У меня есть файл в Интернете (txt). Как это прочитать и проверить, нет ли там? (С#.net 2.0)
Как читать файл из Интернета?
Ответ 1
из http://www.csharp-station.com/HowTo/HttpWebFetch.aspx
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("myurl");
// execute the request
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
// fill the buffer with data
count = resStream.Read(buf, 0, buf.Length);
// make sure we read some data
if (count != 0)
{
// translate from bytes to ASCII text
tempString = Encoding.ASCII.GetString(buf, 0, count);
// continue building the string
sb.Append(tempString);
}
}
while (count > 0); // any more data to read?
// print out page source
Console.WriteLine(sb.ToString());
Ответ 2
Я думаю, что класс WebClient подходит для этого:
WebClient client = new WebClient();
Stream stream = client.OpenRead("http://yoururl/test.txt");
StreamReader reader = new StreamReader(stream);
String content = reader.ReadToEnd();
http://msdn.microsoft.com/en-us/library/system.net.webclient.openread.aspx
Ответ 3
Сначала вы можете загрузить двоичный файл:
public byte[] GetFileViaHttp(string url)
{
using (WebClient client = new WebClient())
{
return client.DownloadData(url);
}
}
Затем вы можете сделать массив строк для текстового файла (предполагая UTF-8 и что это текстовый файл):
var result = GetFileViaHttp(@"http://example.com/index.html");
string str = Encoding.UTF8.GetString(result);
string[] strArr = str.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
Вы получите каждую (кроме пустой) строку текста в каждом поле массива.
Ответ 4
Немного проще:
string fileContent = new WebClient().DownloadString("yourURL");
Ответ 5
альтернативой HttpWebRequest
является WebClient
// create a new instance of WebClient
WebClient client = new WebClient();
// set the user agent to IE6
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.0.3705;)");
try
{
// actually execute the GET request
string ret = client.DownloadString("http://www.google.com/");
// ret now contains the contents of the webpage
Console.WriteLine("First 256 bytes of response: " + ret.Substring(0,265));
}
catch (WebException we)
{
// WebException.Status holds useful information
Console.WriteLine(we.Message + "\n" + we.Status.ToString());
}
catch (NotSupportedException ne)
{
// other errors
Console.WriteLine(ne.Message);
}
пример из http://www.daveamenta.com/2008-05/c-webclient-usage/
Ответ 6
Это слишком просто:
using System.Net;
using System.IO;
...
using (WebClient client = new WebClient()) {
//... client.options
Stream stream = client.OpenRead("http://.........");
using (StreamReader reader = new StreamReader(stream)) {
string content = reader.ReadToEnd();
}
}
"WebClient" и "StreamReader" являются одноразовыми. Содержимое файла будет в "content" var.
Клиентская переменная содержит несколько параметров конфигурации.
Конфигурация по умолчанию может называться:
string content = new WebClient().DownloadString("http://.........");
Ответ 7
Посмотрите на System.Net.WebClient
, в документах даже есть пример получения файла.
Но проверка наличия файла подразумевает запрос файла и отлов исключения, если его там нет.