C# Консольное приложение - выбор определенных c записей из файла CSV и повторная запись в новый файл CSV - PullRequest
0 голосов
/ 17 февраля 2020

У меня есть консольное приложение C#, использующее WebClient для чтения данных из шлюза URL-RP C, а затем записи этих данных в файл CSV.

Мне нужно, как только этот CSV-файл будет записан (и я собираюсь работать с ним как с оператором SQL, так как к этому я привык, но я не могу использовать SQL БД на этот раз) «Выбрать» все записи «Id», «Proctored» и «Score», где столбец «Proctored» представляет собой строку «Yes / Complete», затем взять эти записи и записать их в новый файл CSV.

Есть идеи, как это легко сделать? У меня есть мой базовый c код ниже (этот код выбирает записи с удаленного шлюза и записывает их в файл CSV, пока не получит сообщение «Записи не найдены». Я не могу только извлечь столбцы, которые я хочу, я должен получить все данные (которые включают в себя несколько десятков столбцов), а затем сделать "выбор" на моем конце.

            WebClient client = new WebClient(); //The WebClient calls on the URL-RPC Gateway to get scores
        client.Headers.Add("user-agent", "Mozilla/4.0 (Compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); //Header information for WebClient is REQUIRED--this makes it look like our request comes from a browser and allows proper formatting

        string rpcURL; //Initiates the string we'll use to give the WebClient our URL, after adding our parameters
        string s = ""; //This is the string that gets "read" into the CSV file. Initiate this one "" (empty)
        int page = 1; //The page number. Gateway only allows us to call one page at a time (about 200 records.) So we have to check multiple pages until we get no more data returned, instead, we'll get the phrase "No records found"

        while (!s.Contains("No records found")) //When gateway returns "No Records Found" we know we've reached the last page of data we need to get.
        {
            rpcURL = "https://api.WEBSITE.com/urlrpc?method=getPlacementReport&username=" + userName + "&password=" + passWord + "&class_code=" + classCode + "&from_date=" + startDate + "&to_date=" + endDate + "&page_num=" + page;
            Console.WriteLine(rpcURL);
            client.Headers.Add("user-agent", "Mozilla/4.0 (Compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
            using (var stream = client.OpenRead(rpcURL))
            using (var sr = new StreamReader(stream))
            {
                s = sr.ReadToEnd();

                Console.WriteLine(s);
                string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string docPath = path + "\\" + "AleksReport.csv";

                if (!s.Contains("No records found")) //This makes sure we delete any old file from a previous call to the gateway if it exists
                {
                    if (File.Exists(docPath))
                    {
                        File.Delete(docPath);
                    }
                    using (StreamWriter writer = new StreamWriter(docPath))
                    {
                        writer.WriteLine(s);
                    }
                }
                else
                {
                    Console.WriteLine("End of records");
                }
            }
            page++;

        }
...