Domanda

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();
    }
}
È stato utile?

Soluzione

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();
        }

enter image description here

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a sharepoint.stackexchange
scroll top