Boxiom
Boxiom

Reputation: 2305

How to read all lines in a file from a URI?

I'm currently reading the content of a .srt like this:

var assetURL = "some url";
var textFromFile = (new WebClient()).DownloadString(assetURL);

However, I need to be able to loop through all lines, like this:

 string[] text = File.ReadAllLines(@"subs.srt");
 foreach (string line in text)
 {
    // Do something
 }

I can't do it like that because File.ReadAllLines does not support URIs. Any idea how I can accomplish this?

Upvotes: 0

Views: 2590

Answers (2)

user2160375
user2160375

Reputation:

You can use StringReader:

using (var sr = new StringReader(textFromFile))
{
    string line;
    while ((line = sr.ReadLine()) != null)
    {
       // sth with a line
    }
}

Why it could be better than splitting by Environment.NewLine? It will handle both cases - when the new line character is \r\n or \n.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460108

You can always split a string by Environment.NewLine with String.Split:

string[] lines = textFromFile.Split(new []{ Environment.NewLine }, StringSplitOptions.None);

Upvotes: 3

Related Questions