c# - 将 XLS 转换为 PDF:GetBytes() 期间出现“数据索引必须是字段中的有效索引”异常
问题描述
我有一个将文件转换为 PDF 的应用程序。它首先将来自 MySQL 的 blob 保存到临时文件中,然后将该临时文件转换为 PDF。仅当我尝试转换 XLS 文件时,才会在 GetBytes() 处收到此“数据索引必须是字段中的有效索引”异常错误。其他文件类型(BMP、XLSX、DOC、DOCX 等)都可以转换。
private WriteBlobToTempFileResult WriteBlobToTempFile(int id, string fileType)
{
Logger.Log(string.Format("Inside WriteBlobToTempFile() id: {0} fileType: {1}", id, fileType));
WriteBlobToTempFileResult res = new WriteBlobToTempFileResult //return object
{
PrimaryKey = id
};
FileStream fs; // Writes the BLOB to a file
BinaryWriter bw; // Streams the BLOB to the FileStream object.
int bufferSize = 100; // Size of the BLOB buffer.
byte[] outbyte = new byte[bufferSize]; // The BLOB byte[] buffer to be filled by GetBytes.
long retval; // The bytes returned from GetBytes.
long startIndex = 0; // The starting position in the BLOB output.
string connectionString = ConfigurationManager.AppSettings["MySQLConnectionString"]; //connection string from app.config
string path = ConfigurationManager.AppSettings["fileDirectory"]; //get directory from App.Config
try
{
MySqlConnection conn = new MySqlConnection(connectionString);
conn.Open();
//Determine records to convert, retrieve Primary Key and file type
string sql = "SELECT FILE_DATA from " + TableName + " WHERE PK_TSP_DOCS_ID = @id";
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@id", id);
MySqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
while (rdr.Read())
{
// Create a file to hold the output.
fs = new FileStream(path + @"\" + id + "." + fileType, FileMode.OpenOrCreate, FileAccess.Write);
bw = new BinaryWriter(fs);
// Reset the starting byte for the new BLOB.
startIndex = 0;
// Read the bytes into outbyte[] and retain the number of bytes returned.
retval = rdr.GetBytes(rdr.GetOrdinal("FILE_DATA"), startIndex, outbyte, 0, bufferSize);
// Continue reading and writing while there are bytes beyond the size of the buffer.
while (retval == bufferSize)
{
bw.Write(outbyte);
bw.Flush();
// Reposition the start index to the end of the last buffer and fill the buffer.
startIndex += bufferSize;
// *****IT FAILS AT THE LINE BELOW*****
retval = rdr.GetBytes(rdr.GetOrdinal("FILE_DATA"), startIndex, outbyte, 0, bufferSize);
// *****IT FAILS AT THE LINE ABOVE*****
}
// Write the remaining buffer.
bw.Write(outbyte, 0, (int)retval);
bw.Flush();
// Close the output file.
bw.Close();
fs.Close();
}
// Close the reader and the connection.
rdr.Close();
conn.Close();
res.FullPath = path + @"\" + id + "." + fileType;
}
catch (Exception ex)
{
res.Error = true;
res.ErrorMessage = string.Format("Failed to write temporary file for record id: {0} of file type: {1}", id.ToString(), fileType);
res.InternalErrorMessage = ex.Message; //string.Format("Caught Exception in WriteBlobToTempPDF(). Stack Trace: {0}", ex.StackTrace);
}
return res;
}
解决方案
这是 Oracle 的 MySQL 连接器/NET 中的一个错误。您可以在https://mysql-net.github.io/AdoNetResults/#GetBytes_reads_nothing_at_end_of_buffer看到,当尝试在缓冲区末尾读取 0 个字节时MySql.Data
抛出一个,但没有其他 ADO.NET 提供程序这样做。IndexOutOfRangeException
您应该切换到MySqlConnector(免责声明:我是贡献者)并使用MySqlDataReader.GetStream()
andStream.CopyTo
方法来简化您的代码:
MySqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
while (rdr.Read())
{
// Create a file to hold the output.
using (var fs = new FileStream(path + @"\" + id + "." + fileType, FileMode.OpenOrCreate, FileAccess.Write))
{
// Open a Stream from the data reader
using (var stream = rdr.GetStream(rdr.GetOrdinal("FILE_DATA"))
{
// Copy the data
stream.CopyTo(fs);
}
}
}
推荐阅读
- javascript - 如何使用来自其他两个字段的时间差的值将自定义列添加到数据表
- r - pandoc“样式”扩展未找到
- java - 如何禁用 EditText 的垂直滚动?
- mongodb - 如何在 mgo bson 中聚合字段类型 map[string]uint32?
- pagespeed - PageSpeedInsights API V5 返回总体速度分数
- c++ - 运算符重载逻辑问题
- jira - Jira:具有多个值和自动完成功能的自定义字段
- powershell - 无法从 SMTP 地址解析租户名称 [FailureCategory=Cafe-HttpProxyException]
- java - 原因:java.io.IOException: CreateProcess error=2, 系统找不到AWS指定的文件
- java - 为什么通过扩展来测试一个类被认为是一种不好的做法?