0

I am developing an API where the file is received a file in HttpPostedFile so I want to read the lines and iterate over the all lines:

public IList<string> ReadTextFileAndReturnData(HttpPostedFile file)
{
   IList<string> _responseList = new List<string>();

   //string result = new StreamReader(file.InputStream).ReadToEnd();
   // Not sure how to get all lines from Stream
   foreach (var line in lines)
   {
      // This is what I want to do
      // IList<string> values = line.Split('\t');
      // string data = values[0];
      // _responseList.Add(data);

   }
    return _responseList;
}
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
  • 1
    Possible duplicate of [What is the shortest way to get the string content of a HttpPostedFile in C#](https://stackoverflow.com/questions/10344449/what-is-the-shortest-way-to-get-the-string-content-of-a-httppostedfile-in-c-shar) – Antoine V Oct 03 '18 at 12:17
  • But the data is available in single string, how do get the list of lines with data? – Prashant Pimpale Oct 03 '18 at 12:19
  • As I tried with `string result = new StreamReader(file.InputStream).ReadToEnd();` but the data is receiving in single string but I want the all line in one list as I stated in question – Prashant Pimpale Oct 03 '18 at 12:21
  • Look at my answer – Antoine V Oct 03 '18 at 12:24

1 Answers1

1
var lines = new List<string>();
using(StreamReader reader = new StreamReader(file.InputStream))
{
    do
    {
        string textLine = reader.ReadLine();
        lines.Add(textLine);  
    } while (reader.Peek() != -1);
}
Antoine V
  • 6,998
  • 2
  • 11
  • 34
  • Thanks, it worked but Is there any other option? because there is another `forloop` who runs after this `do while`, so while doing with `File` class like `var lines = File.ReadLines(file);` it returns an array of List of strings, so lookig for this type solution, Is it possible with `HttpPostedFile` --> that's why I posted the question – Prashant Pimpale Oct 03 '18 at 12:40
  • 1
    @PrashantPimpale I don't know another solution :( – Antoine V Oct 03 '18 at 12:55