Documents added through share point object model does not show up in library
-
08-02-2021 - |
Question
Hi I am using SP Object Model to upload a document to document library as below. Once code executed, if I go site contents the library shows the new document count added. But if go to the library no document is showing. Please guide me if I am missing something within the code.
String fileToUpload = @"C:\YourFile.txt";
String sharePointSite = "http://yoursite.com/sites/demo/";
String documentLibraryName = "Shared Documents";
using (SPSite oSite = new SPSite(sharePointSite))
{
using (SPWeb oWeb = oSite.OpenWeb())
{
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
SPFolder myLibrary = oWeb.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = System.IO.Path.GetFileName(fileToUpload);
FileStream fileStream = File.OpenRead(fileToUpload);
// Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
// Commit
myLibrary.Update();
}
}
Solution
I tested the code snippet in my On-Premise Environment, but a bit difference, the file added into the library will be checkout status, maybe this could be the issue, add a line to check in like below to see if you can see the newly added file in the library:
String fileToUpload = @"C:\mytest.txt";
String documentLibraryName = "Shared Documents";
SPSite site = new SPSite("http://sp/sites/dev/");
using (SPWeb oweb =site.OpenWeb())
{
if (!System.IO.File.Exists(fileToUpload))
throw new FileNotFoundException("File not found.", fileToUpload);
SPFolder myLibrary = oweb.Folders[documentLibraryName];
// Prepare to upload
Boolean replaceExistingFiles = true;
String fileName = System.IO.Path.GetFileName(fileToUpload);
FileStream fileStream = System.IO.File.OpenRead(fileToUpload);
// Upload document
SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);
spfile.CheckIn("TestComment", SPCheckinType.MajorCheckIn);
// Commit
myLibrary.Update();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange