[英]sql bulk copy will not upload data to database using file stream
我正在通過文件上傳控件上傳文件,然后流閱讀器讀取文件itno到數據表,然后sql批量復制將數據表復制到我的sql數據庫中並填充適當的列。 有人看到下面的代碼有什么問題嗎? 我沒有收到錯誤消息,但似乎它已掛在IIS進程上。 我無法從文件夾中刪除csv文件,因為它說該過程仍在進行。
protected void btnUpload_Click(object sender, EventArgs e)
{
//upload file to the gencouploadfiles folder
UploadFile();
//fetch CSV file from the folder
string strFilePath = Server.MapPath("GencoUploadFiles") + "\\" + "GencoUploadFile.txt";
//perform sql bulk copy
PerformBulkCopy(GencoUpload(strFilePath));
//delete the file from the folder
}
public void UploadFile()
{
if (fileUpload1.HasFile)
{
FileInfo fileinfo = new FileInfo(fileUpload1.PostedFile.FileName);
string strCsvFilePath = Server.MapPath("GencoUploadFiles") + "\\" + "GencoUploadFile.txt";
fileUpload1.SaveAs(strCsvFilePath);
}
}
public static DataTable GencoUpload(string filepath)
{
StreamReader sr = new StreamReader(filepath);
string line = sr.ReadLine();
string[] value = line.Split('|');
DataTable dt = new DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split('|');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
return dt;
}
public void PerformBulkCopy(DataTable dt)
{
SqlConnection conStr = new SqlConnection(ConfigurationManager.ConnectionStrings["EDI"].ConnectionString);
using (SqlBulkCopy bulkcopy = new SqlBulkCopy(conStr.ConnectionString))
{
bulkcopy.DestinationTableName = "dbo.GencoUploadTempTable";
bulkcopy.BatchSize = dt.Rows.Count;
conStr.Open();
bulkcopy.WriteToServer(dt);
bulkcopy.Close();
conStr.Close();
}
}
簡化您的代碼; 有很多方法可以將csv放入數據表中-例如,請參見如何將CSV文件讀取到.NET數據表中。 在上面的示例中,看完流后似乎沒有關閉流...在返回之前添加sr.Close(),或者最好將聲明包裝在using()語句中:
public static DataTable GencoUpload(string filepath)
{
DataTable dt = new DataTable();
using(StreamReader sr = new StreamReader(filepath))
{
string line = sr.ReadLine();
string[] value = line.Split('|');
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = sr.ReadLine().Split('|');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
}
return dt;
}
這樣可以防止文件被鎖定。
接下來要檢查的是檢查數據表中是否確實有任何數據。 插入一個斷點並進行測試,以查看您的加載代碼是否確實有效; 您正在向數據表中添加行,但尚未定義列結構(即,您僅提供名稱而不是數據類型,因此可能會遇到轉換問題)。 使用其他方法之一加載文件肯定會更容易:-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.