I want to save attachments to a list, and i'm using the following code:
SPSite site = new SPSite("http://knowitintranet:9797/");
SPWeb web = SPContext.Current.Web;
SPList list = web.Lists.TryGetList("Extern products");
try
{
if (list != null)
{
SPListItem item = list.Items.Add();
if (TextBox_Name.Text == string.Empty &&
TextBox_ProdNum.Text == string.Empty &&
TextBox_ListPrice.Text == string.Empty &&
TextBox_Color.Text == string.Empty &&
TextBox_MoreInfo.Text == string.Empty)
{
Label_Exception.Text = "Please enter values!";
Label_Exception.Visible = false;
}
else
{
item["Title"] = TextBox_Name.Text;
item["ProductNumber"] = TextBox_ProdNum.Text;
item["ListPrice"] = TextBox_ListPrice.Text;
item["Color"] = TextBox_Color.Text;
item["MoreInformation"] = TextBox_MoreInfo.Text;
if (FileUpload_Pic.PostedFile != null && FileUpload_Pic.HasFile)
{
Stream fStream = FileUpload_Pic.PostedFile.InputStream;
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
fStream.Dispose();
SPAttachmentCollection attachments = item.Attachments;
string fileName = Path.GetFileName(FileUpload_Pic.PostedFile.FileName);
attachments.Add(fileName, contents);
//listItem["Attached FileName"] = fileName; // store the name of the file in a column for future requirements
}
if (FileUpload_Doc.PostedFile != null && FileUpload_Doc.HasFile)
{
Stream fStream = FileUpload_Doc.PostedFile.InputStream;
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
fStream.Dispose();
SPAttachmentCollection attachments = item.Attachments;
string fileName = Path.GetFileName(FileUpload_Doc.PostedFile.FileName);
attachments.Add(fileName, contents);
}
item.Update();
//Rensar texboxarna
TextBox_Name.Text = string.Empty;
TextBox_ProdNum.Text = string.Empty;
TextBox_ListPrice.Text = string.Empty;
TextBox_Color.Text = string.Empty;
TextBox_MoreInfo.Text = string.Empty;
TextBox_Search.Text = string.Empty;
site.Dispose();
}
}
}
catch (Exception)
{
Label_Exception.Text = "List doesn't exist!";
}
Everything works fine, but it saves only one attachment (the fileUpload_pic) control.
Any suggestions?
/Kristian