读取上传的文件作为字符串数组

时间:2018-10-19 08:51:03

标签: c# asp.net-web-api

我正在上传一个多行文本文档文件。我需要从文档中提取某些行,然后以字节数组的形式存储在数据库中。
我已经能够创建一个显示所有换行符的字符串,但是不确定如何创建字符串数组,以便可以逐行编辑。

  public async Task<string> Upload()
    {
        // get Id of GSM
        string id = HttpContext.Current.Request.Form["id"];
        // get Current logged in user
        var userId = User.Identity.GetUserId();

        var provider = new MultipartMemoryStreamProvider();
        var test = await Request.Content.ReadAsMultipartAsync(provider);

        // extract file name and file contents
        var fileNameParam = provider.Contents[0].Headers.ContentDisposition.Parameters.FirstOrDefault(p => p.Name.ToLower() == "filename");
        string fileName = (fileNameParam == null) ? "" : fileNameParam.Value.Trim('"');

        //read as byte array
        byte[] file = await provider.Contents[0].ReadAsByteArrayAsync();
        // read as string
        string text = System.Text.Encoding.UTF8.GetString(file);

       // Convert to string array???

        var result = string.Format("Received '{0}' with length: {1}", fileName, file.Length);
        return text;

    }

1 个答案:

答案 0 :(得分:0)

这将从上传的文件中逐行读取文本文件,然后将要保留的行写入具有基础内存流的流写入器,而不仅仅是调用.ToArray()以获取所需的字节数组存储在数据库中。 代码中的SomeCondition将确定要保留的行。

byte[] byteArray;
using (var targetStream = new MemoryStream())
using (var writer = new StreamWriter(targetStream))
using (var reader = new StreamReader(await provider.Contents[0].ReadAsStreamAsync()))
{
    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        if(SomeCondition)
           writer.WriteLine(line);
    }
    byteArray = targetStream.ToArray();
}