Reputation: 4283
I was wondering, at the moment, the client uploads a file to a directory on the server where the server can then use the file (csv file) to update a SQL database.
Is that the only way the server can use that file? For it to first be uploaded to the server? Or can you use that file without uploading it to a directory of the server?
(using visual studio 2012, C# and asp.net)
Code update---
asp Uploading the file. (I know the code can be cleaner an written better, but my testing code is never clean)
//Uplod file to the server
FileUpload1.SaveAs(serverUploadDir + FileUpload1.FileName);
//Use the Uploaded File to update the sql table
dbConn.UploadCSVToSql(serverUploadDir + FileUpload1.FileName);
The UploadCSVToSql
public void UploadCSVToSql(string filepath)
{
//string filepath = "C:\\Copy of ABI Employee List.csv";
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);
}
}
SqlBulkCopy bc = new SqlBulkCopy(conn.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = "MainDump";
bc.BatchSize = dt.Rows.Count;
conn.Open();
bc.WriteToServer(dt);
bc.Close();
conn.Close();
Upvotes: 3
Views: 2648
Reputation: 3088
I don't see how you would get a file from the client to the server without uploading it, but you don't need to store it to a folder. If you use the
<asp:FileUpload ID="fuMyUpload" runat="server" />
control. you can get the data in a stream and store it in memory.
if (!fuMyUpload.HasFile)
{
lblWarning.Text = "No file Selected";
return;
}
var csvData = Encoding.UTF8.GetString(fuCircuitCsv.FileBytes);
using (var reader = new StringReader(csvData))
{
var headers = reader.ReadLine().Split(',');
while ((line = reader.ReadLine()) != null)
{
var fields = line.Split(',');
}
}
Upvotes: 4
Reputation: 211
If you have a background job running on the server which monitors the folder for any CSV file, then it needs to be uploaded to the server. If that is not the case, then you should be able to process the file in C# only and perform database update.
Upvotes: 0