使用C#向SharePoint上传文件时添加列值
Great to hear you’ve got the basic file upload working! To add column values (metadata) to the file once it’s uploaded, you’ll need to retrieve the corresponding list item from the document library and update its fields. Here’s how to modify your existing SPUploader method:
Modified Code with Metadata Support
class SPAPI { internal void SPUploader(Stream fs, string filename) { // Wrap ClientContext in using block for proper resource disposal using (ClientContext context = new ClientContext("https://....de")) { // Keep your existing credential setup System.Net.ICredentials creds = System.Net.CredentialCache.DefaultCredentials; context.Credentials = creds; context.RequestTimeout = 60000000; // 60-second timeout // Get the target document library (use its display name here) List documentLibrary = context.Web.Lists.GetByTitle("Dokumenten Management System"); context.Load(documentLibrary); context.ExecuteQuery(); // Prepare file upload details FileCreationInformation fileInfo = new FileCreationInformation(); fileInfo.ContentStream = fs; fileInfo.Url = filename; fileInfo.Overwrite = true; // Set to false if you don't want to overwrite existing files // Upload the file to the library root folder Microsoft.SharePoint.Client.File uploadedFile = documentLibrary.RootFolder.Files.Add(fileInfo); context.Load(uploadedFile); context.ExecuteQuery(); // Retrieve the list item linked to the uploaded file ListItem item = uploadedFile.ListItemAllFields; context.Load(item); context.ExecuteQuery(); // Set your column values here — use the COLUMN'S INTERNAL NAME, not display name! // Examples for common field types: // Text field item["DocumentTitle"] = "Project X Initial Report"; // Date field (pass a valid DateTime object) item["UploadDate"] = DateTime.Now; // Number field item["VersionNumber"] = 1; // Choice field (match the exact choice text from the library settings) item["DocumentStatus"] = "Draft"; // Save the updated metadata to SharePoint item.Update(); context.ExecuteQuery(); } } }
Critical Tips for Success:
- Use Internal Column Names: SharePoint’s display names often differ from internal names (e.g., a display name "Document Title" might have an internal name "DocumentTitle"). To find the internal name:
- Go to your document library settings
- Click the column name you want to use
- Check the URL — the internal name is in the
Fieldparameter (e.g.,Field=DocumentTitle)
- Match Field Data Types: Ensure the value you assign matches the column’s type (don’t pass a string to a number field). For lookup fields, use the ID of the target lookup item or a
FieldLookupValueobject. - Resource Management: Wrapping
ClientContextin ausingblock ensures it’s properly disposed, preventing resource leaks.
If you’re working with special field types like managed metadata or people pickers, let me know and I can add tailored examples for those!
内容的提问来源于stack exchange,提问作者Mondblut
相关产品推荐
相关产品推荐

