无法访问已处置的对象。对象名:System.Net.Sockets.NetworkStream

时间:2016-04-11 23:43:03

标签: c# ftpwebrequest csvhelper

我正在使用CsvHelper。在这里,我试图从ftp下载一个csv文件并写入一个类。它抛出错误 - 无法访问已处置的对象。对象名:System.Net.Sockets.NetworkStream。从线 - IEnumerable records = csv.GetRecords()。ToList();

有什么想法吗?

            request.Credentials = new NetworkCredential(ftpUser, ftpPwd);
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.UseBinary = true;

            // Csv file
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        using (TextReader tr = new StreamReader(responseStream))
                        {
                            using (CsvReader csv = new CsvReader(tr))
                            {
                                if (csvUpload.IncludeInvoice) csv.Configuration.RegisterClassMap<PacketUploadInvoiceMasterMap>();
                                else csv.Configuration.RegisterClassMap<PacketUploadBasicMasterMap>();

                                IEnumerable<PacketUploadMaster> records = csv.GetRecords<PacketUploadMaster>().ToList();

                                pumResults = records.ToList();
                            }
                        }
                    }
                }

                response.Close();
            }

2 个答案:

答案 0 :(得分:1)

为了解决这个问题,我必须单独进行文件读取和写入csv,如下所示

using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
using (Stream responseStream = response.GetResponseStream())
{
    if (responseStream != null)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            responseStream.CopyTo(ms);
            streamInByte = ms.ToArray();
        }
    }
}

using (TextReader tr = new StreamReader(new MemoryStream(streamInByte), Encoding.Default))
{
    using (CsvReader csv = new CsvReader(tr))
    {
        // The value used to escape fields that contain a delimiter, quote, or line ending.
        // csv.Configuration.Quote = '"';
        if (csvUpload.IncludeInvoice) csv.Configuration.RegisterClassMap<PacketUploadInvoiceMasterMap>();
        else csv.Configuration.RegisterClassMap<PacketUploadBasicMasterMap>();

        // Remove white space from header
        csv.Configuration.TrimHeaders = true;

        IEnumerable<PacketUploadMaster> records = csv.GetRecords<PacketUploadMaster>().ToList();

        pumResults = records.ToList();
    }
}

答案 1 :(得分:1)

responseStream的使用结束时,它将关闭并释放responseStream及其基础流,这恰好是您的FtpWebResponse response。这就是为什么调用response.Close()会抛出Cannot access a disposed object