【问题标题】:Uploading and parsing a csv file in C#/Core MVC在 C#/Core MVC 中上传和解析 csv 文件
【发布时间】:2021-10-24 03:53:14
【问题描述】:

我尝试使用以下代码解析正在上传的 CSV 文件:

private Dictionary<string, string[]> LoadData(IFormFile file) 
{
    // Verify that the user selected a file
    if (file != null && file.Length > 0) 
    {
        string wwwPath = this.environment.WebRootPath;
        // string contentPath = this.environment.ContentRootPath;

        string path = Path.Combine(wwwPath, "WeeklySchedules");

        if (!Directory.Exists(path)) 
        {
            Directory.CreateDirectory(path);
        }

        string fileName = Path.GetFileName(file.FileName);

        using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create)) 
        {
            file.CopyTo(stream);

            // System.Threading.Thread.Sleep(1000);
            using (TextFieldParser parser = new TextFieldParser(Path.Combine(path, fileName))) 
            {
                parser.TextFieldType = FieldType.Delimited;
                parser.SetDelimiters(",");

                Dictionary<string, string[]> parsedData = new Dictionary<string, string[]>();

                while (!parser.EndOfData) 
                {
                    // Process row
                    string[] fields = parser.ReadFields();
                    int count = 0;

                    if (count++ == 0) 
                    {
                        continue;
                    }

                    var pickup = fields[0]; 
                    var pickupDate = fields[1];
                    var dropoff = fields[2];
                    var dropoffDate = fields[3];
                    var driver = fields[7];

                    var pickupTime = DateTime.Parse(pickupDate).ToLongTimeString();
                    // string[] data = 
                }
            }
        }
    }

    return null;
}

您会注意到,我将上传流的路径传递给解析器,而不是流本身。我尝试在流中传递,但这也不起作用。当我签入 wwwroot/WeeklySchedules 时,该文件就在那里。但是当解析器到达它时,它返回为空。我什至输入了一个 Sleep() 来查看我是否过早地点击了文件。但这并没有什么不同。

我在原始流中遇到了一些奇怪的错误,但文件已写入,这让我感到困惑。

错误是:

stream.ReadTimeout = 'stream.ReadTimeout' 抛出“System.InvalidOperationException”类型的异常

stream.WriteTimeout = 'stream.WriteTimeout' 引发了“System.InvalidOperationException”类型的异常

我已经阅读了一堆关于加载/解析 CSV 文件的技术的博客文章和 SO 问题,但没有一个表明这是一个问题。

有人有什么想法吗?

【问题讨论】:

    标签: c# asp.net-core-mvc text-parsing


    【解决方案1】:

    您的第一个文件流在您第一次使用时仍处于打开状态,您尝试使用 TextFieldParser 再次读取它

        private Dictionary<string, string[]> LoadData(IFormFile file)
        {
            // Verify that the user selected a file
            if (file != null && file.Length > 0)
            {
                string wwwPath = this.environment.WebRootPath;
                // string contentPath = this.environment.ContentRootPath;
    
                string path = Path.Combine(wwwPath, "WeeklySchedules");
    
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
    
                string fileName = Path.GetFileName(file.FileName);
    
                using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
                {
                    file.CopyTo(stream);
                }
    
                // System.Threading.Thread.Sleep(1000);
                using (TextFieldParser parser = new TextFieldParser(Path.Combine(path, fileName)))
                {
                    parser.TextFieldType = FieldType.Delimited;
                    parser.SetDelimiters(",");
    
                    Dictionary<string, string[]> parsedData = new Dictionary<string, string[]>();
    
                    while (!parser.EndOfData)
                    {
                        // Process row
                        string[] fields = parser.ReadFields();
                        int count = 0;
    
                        if (count++ == 0)
                        {
                            continue;
                        }
    
                        var pickup = fields[0];
                        var pickupDate = fields[1];
                        var dropoff = fields[2];
                        var dropoffDate = fields[3];
                        var driver = fields[7];
    
                        var pickupTime = DateTime.Parse(pickupDate).ToLongTimeString();
                        // string[] data = 
                    }
                }
            }
    
            return null;
        }
    
    

    【讨论】:

    • 就是这样。非常感谢!
    【解决方案2】:

    通过文件保存您的代码;在解析器开始读取文件之前,解开 2 个using 语句,以确保文件已完全写入并已正确关闭。

    using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create)) 
    {
        file.CopyTo(stream);
    }
        
    using (TextFieldParser parser = new TextFieldParser(Path.Combine(path, fileName))) 
    {
        // ..
    }
    

    【讨论】:

    • 哦。就是这样!像冠军一样工作。谢谢!
    猜你喜欢
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    • 2012-12-07
    • 1970-01-01
    • 2021-03-21
    相关资源
    最近更新 更多