1. 程式人生 > >C# 對sharepoint 列表的一些基本操作,包括新增/刪除/查詢/上傳檔案給sharepoint list新增資料

C# 對sharepoint 列表的一些基本操作,包括新增/刪除/查詢/上傳檔案給sharepoint list新增資料

操作List前請設定SPWeb的allowUnsafeUpdate = true;

var site = new SPSite("http://stormwind:10000").RootWeb;

site.AllowUnsafeUpdates = true;

 

新增sharepoint list資料

============================================
using Microsoft.SharePoint;

SPWeb site = SPControl.GetContextWeb(Context); 

SPListItemCollection items = site.Lists["ListName"].Items;

SPListItem item = items.Add(); 

item["Field_1"] = OneValue;

item["Field_2"] = TwoValue;

item.Update();


刪除sharepoint list資料
=============================================
using Microsoft.SharePoint;

SPWeb site = SPControl.GetContextWeb(Context);

SPListItemCollection items = site.Lists["ListName"].Items;

items[0].Delete();


上傳檔案到sharepoint
=============================================
using System.IO;

using Microsoft.SharePoint;

if( htmlInputFile1.PostedFile != null )
{
          SPWeb site = new SPSite(destinationURL).OpenWeb(); 
          Stream stream = htmlInputFile1.PostedFile.InputStream;

          byte[] buffer = new bytes[stream.Length];

          stream.Read(buffer, 0, (int) stream.Length);

          stream.Close();

          site.Files.Add(destinationURL, buffer);
}

查詢記錄及更新資料
===============================================
using Microsoft.SharePoint;

SPWeb web = new SPSite("http://nick").OpenWeb("test");  //Open website

web.AllowUnsafeUpdates = true;

SPList list = web.Lists["ListName"];

SPQuery query = new SPQuery();

query.Query = "<Where>"+
          "<And><And>"+
          "<Eq><FieldRef Name=/"Filed_1/"/><Value Type=/"Text/">Test</Value></Eq>" +
          "<Eq><FieldRef Name=/"Filed_2/"/><Value Type=/"Text/">" + (string)OneValue + "</Value></Eq>" +
          "</And>"+
          "<Eq><FieldRef Name=/"Filed_3/"/><Value Type=/"Text/">" + (string)TwoValue + "</Value></Eq>" +
          "</And>"+
          "</Where>";

query.RowLimit = 10;

//查詢
SPListItemCollection items = list.GetItems(query);
try
{
  if (Items.Count != 0)
  {
     //更新sharepoint list 資料
     foreach (SPListItem list in listItems)
     {
         list["Filed_1"] = TextBox1.text.ToString();
         list["Filed_2"] = TextBox2.text.ToString();
         list["Filed_3"] = TextBox3.text.ToString();

         listItem.Update();
     }                       
  }
  else
  {   //將資料記錄新增進sharepoint
      SPListItem addlist = List.Items.Add();

      addlist["Filed_1"] = TextBox1.Text.ToString();
      addlist["Filed_2"] = TextBox2.Text.ToString();
      addlist["Filed_3"] = TextBox3.Text.ToString();

      addlist.Update();
  }
}
catch
{
 
}

時間會記錄下一切。