Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 更新文件_C#_Asp.net_Asp.net Core_Memorystream_Iformfile - Fatal编程技术网

C# 更新文件

C# 更新文件,c#,asp.net,asp.net-core,memorystream,iformfile,C#,Asp.net,Asp.net Core,Memorystream,Iformfile,我需要从系统中读取excel文件,并修改该文件(如删除重复文件),然后将其放入另一个位置。 我正在使用ifformfile 谁能帮我删除文件中的重复项,更新同一个文件,并用重复的值创建一个新文件 这是我要读的文件 var result = new StringBuilder(); using (var reader = new StreamReader(iFormFile.OpenReadStream())) { //read till EOF while (reader.Peek()

我需要从系统中读取excel文件,并修改该文件(如删除重复文件),然后将其放入另一个位置。 我正在使用
ifformfile

谁能帮我删除文件中的重复项,更新同一个文件,并用重复的值创建一个新文件

这是我要读的文件

var result = new StringBuilder();
using (var reader = new StreamReader(iFormFile.OpenReadStream()))
{
  //read till EOF
  while (reader.Peek() >= 0) 
  {
      result.AppendLine(await reader.ReadLineAsync());
  }
}


 public async Task<Stream> ValidateDataFileAsync(Stream stream, CancellationToken token)
    {
        List<string> result = new List<string>();
        using (var reader = new StreamReader(stream))
        {
            while (reader.Peek() >= 0)
           result.Add(await reader.ReadLineAsync());
        }

        HashSet<string> hSet = new HashSet<string>(result);
       return hSet;

首先安装Nuget:

Install-Package WindowsAzure.Storage -Version 9.3.3

制作一个接口
IBlobManager.cs
,它将容纳所有Blob操作:

using System;
using System.IO;
using System.Threading.Tasks;

namespace UploadAzureBlob.Services
{
    public interface IBlobManager
    {
        Task<string> UploadFileToBlobAsync(string fileName, Stream stream);
    }
}
现在,最后在控制器中:

public async Task<string> ValidateDataFileAsync(IFormFile formFile)
{
        List<string> result = new List<string>();

        using (var reader = new StreamReader(formFile.OpenReadStream()))
        {
            //read till EOF
            while (reader.Peek() >= 0)
                result.Add(reader.ReadLineAsync().Result);
        }

        // Filter by repeated items
        result = result.GroupBy(x => x).Where(x => x.Count() > 1).Select(x => x.Key).ToList();

        // Write the List<string> into the MemoryStream using the EPPlus package

        MemoryStream memoryStream = new MemoryStream();
        using (var package = new ExcelPackage())
        {
            var worksheet = package.Workbook.Worksheets.Add("Worksheet 1");
            worksheet.Cells["A1"].LoadFromCollection(result);
            memoryStream = new MemoryStream(package.GetAsByteArray());
        }

        IBlobManager blobManager = new BlobManager();
        string newResourceUri = await blobManager.UploadFileToBlobAsync(formFile.FileName, memoryStream);
        return newResourceUri;
}
公共异步任务ValidateDataFileAsync(IFormFile formFile)
{
列表结果=新列表();
使用(var reader=newstreamreader(formFile.OpenReadStream()))
{
//读到EOF
while(reader.Peek()>=0)
添加(reader.ReadLineAsync().result);
}
//按重复项筛选
result=result.GroupBy(x=>x).Where(x=>x.Count()>1).选择(x=>x.Key).ToList();
//使用EPPlus包将列表写入MemoryStream
MemoryStream MemoryStream=新的MemoryStream();
使用(var package=new ExcelPackage())
{
var工作表=package.Workbook.Worksheets.Add(“工作表1”);
工作表.单元格[“A1”].LoadFromCollection(结果);
memoryStream=新的memoryStream(package.GetAsByteArray());
}
IBlobManager blobManager=新blobManager();
string newResourceUri=wait blobManager.UploadFileToBlobAsync(formFile.FileName,memoryStream);
返回newResourceUri;
}

重复值是什么意思?假设我的excel数据是“1”、“2”、“3”、“1”。这里“1”是重涂的。在这里,我希望我的excel更新为“1”、“2”、“3”,并使用值“1”(即重复值)创建新文件。发布您的excel样本数据,了解有关此样本数据的任何信息,我将在此发布:此文件适用于csv文件。因此将其标记为答案
using System;
using System.IO;
using System.Threading.Tasks;

namespace UploadAzureBlob.Services
{
    public interface IBlobManager
    {
        Task<string> UploadFileToBlobAsync(string fileName, Stream stream);
    }
}
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace UploadAzureBlob.Services
{
    public class BlobManager : IBlobManager
    {
        private CloudBlobClient cloudBlobClient;
        public BlobManager()
        {
            // Retrieve the connection string for blob storage
            string storageConnectionString = "";

            CloudStorageAccount.TryParse(storageConnectionString, out CloudStorageAccount storageAccount);

            // Create the CloudBlobClient that represents the Blob storage endpoint for the storage account.
            cloudBlobClient = storageAccount.CreateCloudBlobClient();
        }

        /// <summary>
        /// Uploads a file to blob storage.
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public async Task<string> UploadFileToBlobAsync(string fileName, Stream stream)
        {
            try
            {
                // Create a container.
                CloudBlobContainer blobContainer = cloudBlobClient.GetContainerReference("test");
                await blobContainer.CreateAsync();

                BlobContainerPermissions perm = await blobContainer.GetPermissionsAsync();
                perm.PublicAccess = BlobContainerPublicAccessType.Container;
                await blobContainer.SetPermissionsAsync(perm);

                // Get a reference to the blob address, then upload the file to the blob.
                var cloudBlockBlob = blobContainer.GetBlockBlobReference(fileName);
                await cloudBlockBlob.UploadFromStreamAsync(stream);

                // Returning the URI of the freshly created resource
                return cloudBlockBlob.Uri.ToString();
            }
            catch (StorageException ex)
            {
                throw;
            }
        }
    }
}
public async Task<string> ValidateDataFileAsync(IFormFile formFile)
{
        List<string> result = new List<string>();

        using (var reader = new StreamReader(formFile.OpenReadStream()))
        {
            //read till EOF
            while (reader.Peek() >= 0)
                result.Add(reader.ReadLineAsync().Result);
        }

        // Filter by repeated items
        result = result.GroupBy(x => x).Where(x => x.Count() > 1).Select(x => x.Key).ToList();

        // Write the List<string> into the MemoryStream using the EPPlus package

        MemoryStream memoryStream = new MemoryStream();
        using (var package = new ExcelPackage())
        {
            var worksheet = package.Workbook.Worksheets.Add("Worksheet 1");
            worksheet.Cells["A1"].LoadFromCollection(result);
            memoryStream = new MemoryStream(package.GetAsByteArray());
        }

        IBlobManager blobManager = new BlobManager();
        string newResourceUri = await blobManager.UploadFileToBlobAsync(formFile.FileName, memoryStream);
        return newResourceUri;
}