c# - CSVReader 在最后一行最后一列抛出错误

标签 c# csv filestream

我在我的项目中使用 CSVReader 在 Windows 服务中读取 .csv 文件。 我们将 .csv 文件传递​​给 CSVReader 以处理该文件并且它工作正常。 但最近我们决定将 csv 文件保存到数据库表并从那里读取。 当用户提交一个csv文件进行处理时,我们的aspx页面会读取csv文件 并将其转换为字节数组并将其保存到数据库中。 并且该服务将读取表并获取字节数组并将其转换为文件流。 此流将传递给 CSVReader 以供进一步工作。 现在它为最后一行最后一列抛出错误。 它仅在保存并从数据库读取之后发生。 我收到以下错误。 不知道如何解决这个问题。

“CSV 似乎在位置‘494’处的记录‘9’字段‘3’附近损坏。当前原始数据:‘

听到的是代码 将文件转换为字节数组......

try
{
     fs = new FileStream(filepath, FileMode.Open);
     fsbuffer = new byte[fs.Length];
     fs.Read(fsbuffer, 0, (int)fs.Length);
}

从数据库读取到字节数组......

myobject.FileByteArray = ObjectToByteArray(row);

public byte[] ObjectToByteArray(DataRow row)
        {
            if (row["fileBytearray"] == null)
                return null;
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                System.IO.MemoryStream ms = new System.IO.MemoryStream();

                bf.Serialize(ms, row["fileBytearray"]);
                return ms.ToArray();
            }
    }

Stream fileStream = new MemoryStream(myobject.FileByteArray)
using (CsvReader csv = 
                        new CsvReader(new StreamReader(fileStream, System.Text.Encoding.UTF7), hasHeader, ','))

最佳答案

我无法重现您的问题,因此,由于没有看到从头到尾的保存和加载,我建议尝试以下方法进行检索:

public MemoryStream LoadReportData(int rowId)
{

  MemoryStream stream = new MemoryStream();

  using (BinaryWriter writer = new BinaryWriter(stream))
  {

    using (DbConnection connection = db.CreateConnection())
    {
      DbCommand selectCommand = "SELECT CSVData FROM YourTable WHERE Id = @rowId";

      selectCommand.Connection = connection;

      db.AddInParameter(selectCommand, "@rowId", DbType.Int32, rowId);
      connection.Open();

      using (IDataReader reader = selectCommand.ExecuteReader(CommandBehavior.SequentialAccess))
      {

        while (reader.Read())
        {

          int startIndex = 0;
          int bufferSize = 8192;

          byte[] buffer = new byte[bufferSize];

          long retVal = reader.GetBytes(0, startIndex, buffer, 0, bufferSize);

          while (retVal == bufferSize)
          {

            writer.Write(buffer);
            writer.Flush();

            startIndex += bufferSize;
            retVal = reader.GetBytes(0, startIndex, buffer, 0, bufferSize);

          }

          writer.Write(buffer, 0, (int)retVal);
        }

      }

    }
  }

  return stream;

}

您需要将 selectCommand sql 和参数替换为您用于返回数据的任何 sql。

此方法使用 SqlDataReader 从适当的行(在我的示例中由 rowId 标识)和列(在我的示例中称为 CSVData)顺序读取字节,这应该避免出路时的任何截断问题(可能是您的 DataTable 对象仅返回前 n 字节)。 MemoryStream 对象可用于将 CSV 文件重新保存到文件系统以进行测试,或直接送入您的 CSVReader。

如果您可以发布您的Save 方法(您实际上将数据保存到数据库中),那么我们也可以检查它以确保那里也没有发生截断。

我现在可以提出的另一个建议是将文件加载到 byte 数组中。如果你打算一次性加载文件,那么你可以简单地替换:

try
{
     fs = new FileStream(filepath, FileMode.Open);
     fsbuffer = new byte[fs.Length];
     fs.Read(fsbuffer, 0, (int)fs.Length);
}

byte[] fileBytes = File.ReadAllBytes(filepath);

关于c# - CSVReader 在最后一行最后一列抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12862993/

相关文章:

c# - WPF:如何在具有不同名称的 for 循环内创建 UserControl 的多个实例?

c# - 文件流.ReadByte : Byte's are never negative numbers?

java - 具有最低和最高价格的产品(数据从文本文件中读取)

C# 反射 : Replace a referenced assembly

c# - C#/.Net 中 'new' 属性的优缺点?

python - 在 pandas 中,如何读取列中包含列表的 csv 文件?

python - 在 pandas 中的 groupby 之后添加一个新列

pdf - Angular2 显示 PDF

c# - 为什么物体永远不动?

php - 从sql语句创建多个CSV文件