2024/02/26(月)02:47
VB.NETでSharePointリストの特定の添付ファイルのコンテンツを更新するコード
Imports System.IO
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Text
Imports System.Threading.Tasks
Module Module1
Sub Main()
Dim siteUrl As String = "https://your-sharepoint-site-url"
Dim username As String = "your-username"
Dim password As String = "your-password"
Dim listName As String = "YourListName"
Dim itemId As Integer = 10 ' 添付ファイルを更新するアイテムのID
Dim attachmentName As String = "file.txt" ' 更新する添付ファイルの名前
Dim filePath As String = "path\to\your\updated-file.txt" ' 更新したいファイルのパス
UpdateAttachmentContent(siteUrl, username, password, listName, itemId, attachmentName, filePath).Wait()
End Sub
Async Function UpdateAttachmentContent(siteUrl As String, username As String, password As String, listName As String, itemId As Integer, attachmentName As String, filePath As String) As Task
Dim credentials As String = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{username}:{password}"))
Using client As New HttpClient()
client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Basic", credentials)
' 添付ファイルを削除
Dim deleteEndpointUrl As String = $"{siteUrl}/_api/web/lists/getbytitle('{listName}')/items({itemId})/AttachmentFiles/getByFileName('{attachmentName}')"
Dim deleteResponse As HttpResponseMessage = Await client.DeleteAsync(deleteEndpointUrl)
If Not deleteResponse.IsSuccessStatusCode Then
Console.WriteLine($"Failed to delete attachment '{attachmentName}'. StatusCode: {deleteResponse.StatusCode}")
Return
End If
' 新しい添付ファイルを追加
Dim fileContent As New StreamContent(File.OpenRead(filePath))
fileContent.Headers.ContentDisposition = New ContentDispositionHeaderValue("form-data") With {
.Name = "file",
.FileName = Path.GetFileName(filePath)
}
Dim multipartContent As New MultipartFormDataContent()
multipartContent.Add(fileContent)
Dim addEndpointUrl As String = $"{siteUrl}/_api/web/lists/getbytitle('{listName}')/items({itemId})/AttachmentFiles/add(FileName='{Path.GetFileName(filePath)}')"
Dim addResponse As HttpResponseMessage = Await client.PostAsync(addEndpointUrl, multipartContent)
If addResponse.IsSuccessStatusCode Then
Console.WriteLine($"Attachment '{attachmentName}' content updated successfully for item with ID {itemId}.")
Else
Console.WriteLine($"Failed to update attachment content. StatusCode: {addResponse.StatusCode}")
End If
End Using
End Function
End Module