Hi @William Ng,
You could apply some type of retry strategy. Please refer to following code
public static bool TryUploadFile(ClientContext ctx, string sourceFilePath, string targetUrl, IDictionary<string, string> fileProperties)
{
using (var fileStream = new FileStream(sourceFilePath, FileMode.Open))
{
var fileInfo = new FileCreationInformation()
{
ContentStream = fileStream,
Overwrite = true,
Url = Path.GetFileName(sourceFilePath)
};
var targetFolder = ctx.Web.GetFolderByServerRelativeUrl(targetUrl);
var uploadFile = targetFolder.Files.Add(fileInfo);
var listItem = uploadFile.ListItemAllFields;
foreach (var p in fileProperties)
{
listItem[p.Key] = p.Value;
}
return TrySaveListItem(listItem, TimeSpan.FromSeconds(2));
}
}
private static bool TrySaveListItem(ListItem listItem, TimeSpan retryInterval, int retryCount = 3)
{
while (true)
{
try
{
listItem.Update();
listItem.Context.ExecuteQuery();
return true;
}
catch
{
if (--retryCount == 0) return false;
Thread.Sleep(retryInterval);
}
}
}
If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.