I had a FileUpload control earlier to upload each file individually in the database. But now I want to be able to do bulk upload.
My requirement is that a csv file contains the filename and filepath, I need to upload the csv using FileUpload and eventually run a code that reads the csv and inserts each file into a table ApplicantAttachment. ApplicantAttachment has columns fileName (NVARCHAR), FilePath(NVARCHAR), Attachment (VARBINARY). In this attachment column, I need to save the binary format of the files mentioned in the csv.
MY CSV looks like this
FileName FilePath
dl-54a.pdf c:\users\abc\desktop\dl-54a.pdf
xyz.doc c:\users\abc\desktop\xyz.doc
I wish I could do something like this. But I know we caanot assing filename etc to the Fileupload object. Any suggestions would be helpful.
<asp:FileUpload ID="csvFile" runat="server" Width="400" /></td>
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="btnUpload_Click" /></td>
protected void btnUpload_Click(object sender, EventArgs e)
{
if (csvFile.HasFile)
{
List<string[]> filesToUpload = parseCSV(csvFile.PostedFile.FileName);
SaveFiles(filesToUpload);
}
}
public List<string[]> parseCSV(string path)
{
List<string[]> parsedData = new List<string[]>();
try
{
using (StreamReader readFile = new StreamReader(path))
{
string line;
string[] row;
while ((line = readFile.ReadLine()) != null)
{
if (!readFile.ReadLine().Contains("ApplicantId"))
{
row = line.Split(',');
parsedData.Add(row);
}
}
}
}
catch (Exception e)
{
;
}
return parsedData;
}
private void SaveFiles(List<string[]> files)
{
foreach (string[] attachment in files)
{
using (DataClasses1DataContext db = new DataClasses1DataContext())
{
FileUpload fu = new FileUpload();
fu.FileName = attachment[1].ToString();
if (fu.HasFile)
{
ApplicantAttachment aa1 = new ApplicantAttachment();
aa1.Filename = attachment[0].ToString();
aa1.FileType = fu.PostedFile.ContentType;
aa1.Attachment = fu.FileBytes;
db.ApplicantAttachments.InsertOnSubmit(aa1);
db.SubmitChanges();
}
}
}
}
This is what works. FileUpload cant be used.