how to read multiple files txt c#

Hi I'm trying to read 2 txt files, from an asmx web service, the reason is that in file 1 I have random letters of which I have to find matching words from file 2. But I do not know how to read the files.

this is the webService.This is the way I am doing it. the idea is to read the first file and get the routes to others, which you read and add them to a list,but if you have another idea I would appreciate sharing

namespace NewShoreApp
{        
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]

    public class WebService : System.Web.Services.WebService
    {

        [WebMethod]
        public string ReadData()
        {

            string[] lines = File.ReadAllLines(@"C:\Users\thoma\source\repos\NewShoreApp\NewShoreApp\Data\CONTENIDO.txt");

            List<string> list = new List<string>();

            foreach (var line in lines)
            {

                string data= File.ReadAllLines(line); //'Cannot implicitly convert type string[] to string'

                list.AddRange(data); //Cannot convert from string to system.collections.generic IEnumerable<string>
            }

                return ".";                        
            }
    }
}

this is the controller where I upload the files and add them in an array.

namespace NewShoreApp.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {

            return View();
        }


        [HttpPost]
        public ActionResult Index(HttpPostedFileBase[] files)
        {

            if (ModelState.IsValid)
            {
                try
                {
                    foreach (HttpPostedFileBase file in files)
                    {
                        if (file != null)
                        {
                            var ServerPath = Path.Combine(Server.MapPath("~/Data"), Path.GetFileName(file.FileName));

                            file.SaveAs(ServerPath);
                        }
                    }                    
                    ViewBag.FileStatus = "File uploaded successfully.";
                }

                catch (Exception)   
                {

                    ViewBag.FileStatus = "Error while file uploading.";
                }

            }
            return View("Index");
        }

    }
}

this is the model

namespace NewShoreApp.Models
{
    public class Data
    {
        // 
        [DataType(DataType.Upload)]
        [Display(Name = "Upload File")]
        [Required(ErrorMessage = "Please choose file to upload.")]
        public HttpPostedFileBase[] files { get; set; }

    }
}

Upvotes: 1

Views: 6740

Answers (3)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

The problem occurred because File.ReadAllLines() returns array of strings (string[]), you can convert it into List<string> by using ToList() method:

string[] lines = File.ReadAllLines(@"C:\Users\thoma\source\repos\NewShoreApp\NewShoreApp\Data\CONTENIDO.txt");

List<string> list = lines.ToList();

If you want to read multiple files in the same folder and add all contents to a list of strings, use Directory.GetFiles() or Directory.EnumerateFiles() and iterate each file paths before using ReadAllLines():

List<string> paths = Directory.EnumerateFiles(@"C:\Users\thoma\source\repos\NewShoreApp\NewShoreApp\Data\", "*.txt").ToList();

foreach (string filePath in paths)
{
    string[] lines = File.ReadAllLines(filePath);

    list.AddRange(lines.ToList());
}

In multithreaded environment, you should consider using Parallel.ForEach with similar setup like above over foreach loop:

List<string> paths = Directory.EnumerateFiles(@"C:\Users\thoma\source\repos\NewShoreApp\NewShoreApp\Data\", "*.txt").ToList();
Parallel.ForEach(paths, current => 
{
    string[] lines = File.ReadAllLines(current);

    list.AddRange(lines.ToList());
});

Upvotes: 4

L0uis
L0uis

Reputation: 721

If the problem is this line:

string data= File.ReadAllLines(line); //'Cannot implicitly convert type string[] to string'

The variable lines is an array of each line as a string, that you already called above.

Just cast the array of lines to a list if you want a list of lines:

var list = new List<string>(data); 

Upvotes: 2

A Farmanbar
A Farmanbar

Reputation: 4798

The best way of read multiple txt files parallel is using ThreadPool.

ThreadPool.QueueUserWorkItem(ReadFile, path);

and the ReadFile method is here

public static void ReadFile(Object path)
{
 string content = File.ReadAllLines(@path)
 // do what you need 
}

Upvotes: 2

Related Questions