我想使用c#将项目添加到图片库中。这就是我将字段添加到普通项目的方式:
var item = list.Items.Add();
item["Title"] = "Item title";
item.Update();
我该如何添加图片?图片存储在文件系统中,即c:\ myfile.png我iamgine我需要使用SPFile但不确定如何。
答案 0 :(得分:3)
这是从文件
创建byte []的方法private byte [] StreamFile(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read);
// Create a byte array of file stream length
byte[] ImageData = new byte[fs.Length];
//Read block of bytes from stream into the byte array
fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));
//Close the File Stream
fs.Close();
return ImageData;
}
// then use the following to add the file to the list
list.RootFolder.Files.Add(fileName, StreamFile(fileName));
答案 1 :(得分:1)
就像向文档库添加文件一样简单。以下是可帮助您完成此操作的代码段。我已经从这个link获取代码,因为格式化不合适我在这里粘贴了一个干净的版本
try
{
byte[] imageData = null;
if (flUpload != null)
{
// This condition checks whether the user has uploaded a file or not
if ((flUpload.PostedFile != null) && (flUpload.PostedFile.ContentLength > 0))
{
Stream MyStream = flUpload.PostedFile.InputStream;
long iLength = MyStream.Length;
imageData = new byte[(int)MyStream.Length];
MyStream.Read(imageData, 0, (int)MyStream.Length);
MyStream.Close();
string filename = System.IO.Path.GetFileName(flUpload.PostedFile.FileName);
SPPictureLibrary pic = (SPPictureLibrary)SPContext.Current.Web.Lists["Images"];//Images is the picture library name
SPFileCollection filecol = ((SPPictureLibrary)SPContext.Current.Web.Lists["Images"]).RootFolder.Files;//getting all the files which is in pictire library
filecol.Add(filename, imageData);//uploading the files to picturte library
}
}
}
catch (Exception ex)
{
//handle it
}