データベースからExcelファイルにデータを保存するSQLサーバー用のCLRアセンブリを作成しています。データベースから無効な文字エラーが発生するまでは問題なく動作します。
System.ArgumentException:''、16進値0x04は、無効な文字です。
問題は、ファイルがロックされたままであり、このCLRプロシージャが次に実行されるまでファイルを削除できないことです。エラーが発生したときにファイルのロックを解除したり、ファイルを削除したりするにはどうすればよいですか?
別の質問?無効な文字でExcelファイルを保存できますか?
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using ClosedXML.Excel;
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Assert, Name = "FullTrust")]
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static void createExcel(SqlString procName, SqlString fileName, SqlString filePath, SqlXml xmlParams, out SqlBoolean result)
{
result = false;
DataSet exportData = new DataSet();
if (procName.Value == string.Empty)
throw new Exception("Procedure name value is missing.");
if (filePath.Value == string.Empty)
throw new Exception("Missing file path location.");
if (fileName.Value == string.Empty)
throw new Exception("Missing name of file.");
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
using (SqlCommand getOutput = new SqlCommand())
{
getOutput.CommandText = procName.ToString(); ;
getOutput.CommandType = CommandType.StoredProcedure;
getOutput.CommandTimeout = 300;
getOutput.Connection = conn;
conn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(getOutput))
{
da.AcceptChangesDuringFill = false;//drugače da pokliče na koncu AcceptChanges in hasChanges je vedno false
da.Fill(exportData);
conn.Close();
da.Dispose();
try
{
if (exportData.HasChanges())
{
using (XLWorkbook xlWb = new XLWorkbook(XLEventTracking.Disabled))
{
xlWb.Worksheets.Add(exportData.Tables[0]);
xlWb.SaveAs(filePath.ToString() + fileName.ToString());
result = true;
}
}
}
finally
{
exportData.Dispose();
}
}
}
}
}