Search code examples
c#asp.netasp.net-mvcweb-servicesasmx

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; }

    }
}

Solution

  • 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());
    });