string strConn = ConfigurationManager.ConnectionStrings["Connection"].ConnectionString.ToString();
SqlConnection con = new SqlConnection(strConn);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftpserver");
request.Credentials = new NetworkCredential("username", "pass");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responsestream = response.GetResponseStream();
StreamReader sr = new StreamReader(responsestream);
SqlBulkCopy bc = new SqlBulkCopy(con.ConnectionString, SqlBulkCopyOptions.TableLock);
try
{
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);
}
}
bc.DestinationTableName = "CSVTest";
bc.BatchSize = dt.Rows.Count;
con.Open();
bc.WriteToServer(dt);
//File.Open(str1, FileMode.Open, FileAccess.Read, FileShare.None);
using (var writer = new StreamWriter(responsestream))
{
writer.Write("");
}
}
catch (ObjectDisposedException a)
{
Console.WriteLine("Caught: {0}", a.Message);
}
finally
{
//Closing Bulk Copy
bc.Close();
//Closing Sql Connection
con.Close();
//Dispose method internally calls Close..So you dont need to call the close explicitly.
sr.Dispose();
}
从 ftp 读取文件服务器完成读取文件时循环引发错误无法访问已处置的对象。对象名称:“System.Net.Sockets.NetworkStream”。