转换代码以读取字节并存储数据

时间:2018-07-20 08:34:06

标签: c# csv filereader

我正在努力增强某人的代码。 基本上,这个家伙写了它,以便直接从单独的控制台项目上的文件夹路径读取csv文件,其代码如下:

static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.WriteLine("Usage: ImportUser.exe <input.csv>");
            return;
        }

        string inputFileDirectory = args[0];
        string outputFileDirectory = Path.Combine(Environment.CurrentDirectory, "error.csv");

        var i = 1;
        var j = 0;

        using (var reader = new StreamReader(inputFileDirectory))
        {
            using (var writer = new StreamWriter(outputFileDirectory, false))
            {
                var csv = new CsvReader(reader);
                csv.Configuration.RegisterClassMap<RecordMapper>();
                csv.Configuration.HeaderValidated = null;
                var outCsv = new CsvWriter(writer);

                var records = csv.GetRecords<Record>();

                List<Record> BadRecords = new List<Record>();

                foreach (var record in records)
                {
                    Console.WriteLine("Processing record " + i);
                    record.Index = i++;
                    try
                    {
                        using (var db = new dcIngressDataContext())
                        {
                            ProcessRecord(db, record);
                        }
                    }
                    catch (Exception ex)
                    {
                        j++;
                        {
                            record.Error = ex.ToString();
                            Console.WriteLine(ex.ToString());
                            Console.WriteLine(record);
                            outCsv.WriteRecord<Record>(record);
                            outCsv.NextRecord();
                        }
                    }
                }
            }
        }
        Console.WriteLine(i - 1 + " records processed.");
        if (j > 0)
        {
            Console.WriteLine(j + " records not added. See error.csv for details.");
        }
        Console.WriteLine("Press Any Key To Continue...");
        Console.ReadLine();
    }

我必须将其转换为api方法,然后将其解析为Byte []中的文件数据。如何替换/转换第一部分,以便它读取byte []并将数据放入列表中?这是我从控制器->存储库-> webapi中获得的代码。

[HttpPost]
    public ActionResult UserImport(HttpPostedFileBase uploadFile)
    {
        Session currentSession = Helpers.GetCurrentSession(User.Identity);
        var companyid = currentSession.CompanyId;

        try
        {
            byte[] data;
            if (uploadFile.ContentLength > 0)
            {
                using (Stream inputStream = uploadFile.InputStream)
                {
                    MemoryStream memoryStream = inputStream as MemoryStream;
                    if (memoryStream == null)
                    {
                        memoryStream = new MemoryStream();
                        inputStream.CopyTo(memoryStream);
                    }
                    data = memoryStream.ToArray();
                    var NewFile = new ImportUsers
                    {
                        CompanyId = companyid,
                        Content = data,
                    };

                    var upld = repository.Attachments.importUsers(NewFile);
                }
            }
            ViewBag.Message = "File Uploaded Successfully!!";
            return View();
        }
        catch
        {
            ViewBag.Message = "File upload failed!!";
            return View();
        }
        return View();
    }

ApiRepository

public WebApiResponse<ImportUsers> importUsers(ImportUsers file)
    {
        var response = Client.PostAsJsonAsync("api/attachments/importusers", file).Result;

        if (response.IsSuccessStatusCode)
        {
            var apiResponse = response.Content.ReadAsAsync<WebApiResponse<ImportUsers>>().Result;
            if (apiResponse.Status == ReturnStatus.SessionInvalid)
            {
                throw new InvalidSessionException();
            }
            if (apiResponse.Status == ReturnStatus.NoAccess)
            {
                throw new NoAccessException();
            }
            return apiResponse;
        }
        else
        {
            return new WebApiResponse<ImportUsers>()
            {
                Status = ReturnStatus.Failed,
                Error = "Error connecting to server. " + response.ReasonPhrase,
                Result = null
            };
        }
    }

我将从此处将字节传递给webApi。我创建了一个方法并复制了代码,但它无法正常工作。

[HttpPost]
    [Route("api/attachments/importusers")]
    public WebApiResponse ImportUser([FromBody]ImportUserDTO value)
    {
        var response = new WebApiResponse();

        var i = 1;
        var j = 0;
        using (var reader = new StreamReader(inputFileDirectory))
        {
            using (var writer = new StreamWriter(outputFileDirectory, false))
            {
                var csv = new CsvReader(reader);
                csv.Configuration.RegisterClassMap<RecordMapper>();
                csv.Configuration.HeaderValidated = null;
                var outCsv = new CsvWriter(writer);

                var records = csv.GetRecords<Record>();

                List<Record> BadRecords = new List<Record>();

                foreach (var record in records)
                {
                    Console.WriteLine("Processing record " + i);
                    record.Index = i++;
                    try
                    {
                        using (var db = new ApplicationDbContext())
                        {
                            ProcessRecord(db, record);
                        }
                    }
                    catch (Exception ex)
                    {
                        j++;
                        {
                            record.Error = ex.ToString();
                            Console.WriteLine(ex.ToString());
                            Console.WriteLine(record);
                            outCsv.WriteRecord<Record>(record);
                            outCsv.NextRecord();
                        }
                    }
                }
            }
        }
        Console.WriteLine(i - 1 + " records processed.");
        if (j > 0)
        {
            Console.WriteLine(j + " records not added. See error.csv for details.");
        }
        Console.WriteLine("Press Any Key To Continue...");
        Console.ReadLine();

        return response;

    }

1 个答案:

答案 0 :(得分:0)

我仅使用MemoryStream就找到了解决方案

Stream stream = new MemoryStream(value.Content);

替换

using (var reader = new StreamReader(inputFileDirectory))

使用

using (var reader = new StreamReader(stream))