Programatically target default document library for file upload in SP16 - c#

I made a C# application for uploading files to SharePoint. So far it Works as intended, on all document libraries except the default one. Everytime it throws an exception : List 'Documents' does not exist at site with URL 'http://...'
I've tried with "Shared Documents" as well, but same result. Does the default library have some internal name I'm not aware of?
The code for uploading is as follows:
// Get the SharePoint context
ClientContext context = new ClientContext(domain);
// Open the web
var web = context.Web;
String[] files = System.IO.File.ReadAllLines(args[0]);
foreach (String file in files)
{
// Create the new file
var newFile = new FileCreationInformation
{
Content = System.IO.File.ReadAllBytes(file),
Url = Path.GetFileName(file),
Overwrite = true
};
// Get a reference to the document library
var docs = web.Lists.GetByTitle(library);
var uploadFile = docs.RootFolder.Files.Add(newFile);
// Upload the document
context.Load(uploadFile);
}

First of all, it is much safer to get list by url, not title.
using (ClientContext context = new ClientContext("https://sharepoint.domain.com"))
{
context.Load(context.Web, w => w.ServerRelativeUrl);
context.ExecuteQuery();
List list = context.Web.GetList($"{context.Web.ServerRelativeUrl.TrimEnd('/')}/Shared Documents");
}
Also don't forget to dispose the object context.
Check enabled alternate languages (Site settings > Site Administration > Language settings). You may have more enabled languages and the default one could be different then you expect. Each language holds its own list name.

Related

C# - CSOM - Upload a file to a subdirectory in Sharepoint Online

I'm trying to upload a file to SharePoint Online and I got this sample code:
var uploadFile = list
.RootFolder
.Folders
.GetByPath(ResourcePath.FromDecodedUrl("A"))
.Files
.Add(newFile);
ctx.Load(uploadFile);
await ctx.ExecuteQueryAsync();
Which works perfectly fine, so everything around it works. But apparently this snippet
var uploadFile = list
.RootFolder
.Folders
.GetByPath(ResourcePath.FromDecodedUrl("A/B"))
.Files
.Add(newFile);
ctx.Load(uploadFile);
await ctx.ExecuteQueryAsync();
Throws System.IO.DirectoryNotFoundException even though both directories exist. So how can I upload a file to the subdirectory "B"?
Try to upload file like this:
public static void UploadFile(ClientContext context,string uploadFolderUrl, string uploadFilePath)
{
var fileCreationInfo = new FileCreationInformation
{
Content = System.IO.File.ReadAllBytes(uploadFilePath),
Overwrite = true,
Url = Path.GetFileName(uploadFilePath)
};
var targetFolder = context.Web.GetFolderByServerRelativeUrl(uploadFolderUrl);
var uploadFile = targetFolder.Files.Add(fileCreationInfo);
context.Load(uploadFile);
context.ExecuteQuery();
}
using (var ctx = new ClientContext(webUri))
{
ctx.Credentials = credentials;
UploadFile(ctx,"LibName/FolderName/Sub Folder Name/Sub Sub Folder Name/Sub Sub Sub Folder Name",filePath);
}
Please check out another similiar thread here:
Alternative Save/OpenBinaryDirect methods for CSOM for SharePoint Online

Downloading images from publicly shared folders and sub-folders on Dropbox

This is similar to my previous question:
Downloading images from publicly shared folder on Dropbox
I have this piece of code (simplified version) that needs to download all images from publicly shared folder and all sub-folders.
using Dropbox.Api;
using Dropbox.Api.Files;
...
// AccessToken - get it from app console
// FolderToDownload - https://www.dropbox.com/sh/{unicorn_string}?dl=0
using (var dbx = new DropboxClient(_dropboxSettings.AccessToken))
{
var sharedLink = new SharedLink(_dropboxSettings.FolderToDownload);
var sharedFiles = await dbx.Files.ListFolderAsync(path: "", sharedLink: sharedLink);
// var sharedFiles = await dbx.Files.ListFolderAsync(path: "", sharedLink: sharedLink, recursive: true);
// "recursive: true" throws: Error in call to API function "files/list_folder": Recursive list folder is not supported for shared link.
foreach (var entry in sharedFiles.Entries)
{
if (entry.IsFile)
{
var link = await dbx.Sharing.GetSharedLinkFileAsync(url: _dropboxSettings.FolderToDownload, path: "/" + entry.Name);
var byteArray = await link.GetContentAsByteArrayAsync();
}
if (entry.IsFolder)
{
var subFolder = entry.AsFolder;
// var folderContent = await dbx.Files.ListFolderAsync(path: subFolder.Id);
// var subFolderSharedLink = new SharedLink(???);
}
}
}
How do I list entries of all sub-folders?
For any given subfolder, to list its contents, you'll need to call back to ListFolderAsync again, using the same sharedLink value, but supplying a path value for the subfolder, relative to the root folder for the shared link.
For example, if you list the contents of the folder shared link, and one of the entries is a folder with the name "SomeFolder", to then list the contents of "SomeFolder", you would need to make a call like:
await dbx.Files.ListFolderAsync(path: "/SomeFolder", sharedLink: sharedLink);

Open Local HTML files in Xamarin.Forms Web View NOT in Assets Folder

I am trying to open a multipage HTML web page (i.e. test.html, test.css and test.js) which has been downloaded dynamically (thefore can't use assets) and stored in the apps internal storage (Xamarin.Essentials.FileSystem.AppDataDirectory).
The URL I am trying to use is as follows:
file:///data/user/0/com.test/files/HTML/Test.html
However I just get file not found.
var filesToDownload = new string[] { "http://myserver/test/test.html", "http://myserver/test/test.css" };
var directory = System.IO.Path.Combine(Xamarin.Essentials.FileSystem.AppDataDirectory, "HTML");
if (System.IO.Directory.Exists(directory))
{
System.IO.Directory.Delete(directory, true);
}
System.IO.Directory.CreateDirectory(directory);
using (var wc = new System.Net.WebClient())
{
foreach (var f in filesToDownload)
{
wc.DownloadFile(f, System.IO.Path.Combine(directory, System.IO.Path.GetFileName(f)));
}
}
var source = new UrlWebViewSource
{
Url = System.IO.Path.Combine("file://" + directory, "Test.html")
};
WebView1.Source = source;
There are several points you have to make sure:
1 Add the Xamarin.Essentials NuGet package to each project
2 http://myserver/test/test.html and http://myserver/test/test.css are existed and accessible.
3 The file name of webview source should be the same with the file name you have written to your storage. Not Test.html, but test.html
So
Url = System.IO.Path.Combine("file://" + directory, "Test.html") should be modified to
Url = System.IO.Path.Combine("file://" + directory, "test.html")

How to upload a file in share point server from a local machine connected through lan using c#

I am really new to this share point stuffs.We have a share point server with admin account in it and i was connecting it from my local machine through ip and share point port manually.
Nut i need to write a program which needs to upload the files into the share point server from the local machine to server. Is it possible in using winforms ? or only possible in web services.?
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();
}
}
tried using the above code and i getting error from the following line
using (SPSite oSite = new SPSite(sharePointSite))
and the error was
"The Web application at http://server:port/ could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application"
and am not able to upload the file.
But if i copied and paste the same URL in my local machine i can able to access the sharepoint deployed in server and i can even upload files manually from my local machine.
How to upload a file in sharepoint server from the local machine connected with LAN..??
siteURL = Main URl of the sharepoint (eg) "http://10.0.0.14:48487/";
documentListName = any of the folders in shrepoint (eg) Shared Documents
documentName = name of the file (eg)sampleword.docx , readme.txt etc
documentStream = the byte format of the file which we going to upload.
(eg)byte[] bytefile = System.IO.File.ReadAllBytes(filepath+filename);
public static void UploadDocument(string siteURL, string documentListName, string documentListURL,string documentName, byte[] documentStream = null)
{
try
{
using (SP.ClientContext clientContext = new SP.ClientContext(siteURL))
{
#region"Only if you have credentials"
NetworkCredential Cred = new NetworkCredential("username", "password");
clientContext.Credentials = Cred;
#endregion
SP.List documentsList = clientContext.Web.Lists.GetByTitle(documentListName);
var fileCreationInformation = new SP.FileCreationInformation();
//Assign to content byte[] i.e. documentStream
fileCreationInformation.Content = documentStream;
//Allow owerwrite of document
fileCreationInformation.Overwrite = true;
//Upload URL
fileCreationInformation.Url = documentName;
Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(
fileCreationInformation);
uploadFile.ListItemAllFields.Update();
clientContext.ExecuteQuery();
}
}
catch (Exception ex)
{
}
}
}
This works perfect for me :) :)
make sure your connecting to an existing site collection. the error you have received is quite self explainitory, it cannot find the site collection you have pointed it at. check your string sharePointSite to make sure there isn't a typo and that it's accessing the correct root site collection. Remember with SharePoint SPSite = Site Collection SPWeb = a website in a site collection.
i can't see any glaring errors in your code without running something up myself except to make sure that when you are calling oSite.openweb() it's for a single site within the site collection.

How to upload document with metadata to avoid duplicate versioning?

I am upload document to document library along with metadata using server object model in sharepoint foundation 2010. I am using following code
// Initialize instance of existing site collection
using (SPSite site = new SPSite(siteUrl))
{
//Initailize instance of exiting web site (for e.g. Team Site)
using (SPWeb web = site.RootWeb)
{
//Get list with specified name in the existing web site
SPList list = web.Lists[libraryName];
//Get the collection of folders in the existing web site
String url = list.RootFolder.ServerRelativeUrl.ToString();
SPFolderCollection folders = web.GetFolder(url).SubFolders;
//Add new folder in the exiting collection of folders
SPFolder folder = folders.Add(folderName);
//SPFolder folder = web.GetFolder(siteUrl + "/" + libraryName + "/" + folderName);
//byte[] fileContents = System.IO.File.ReadAllBytes(#fileUrl);
//Add file in the newly added folder with overwrite
var overWrite = true;
SPFile file = folder.Files.Add(saveFileWithName, fileContents, overWrite);
//Get the list item of the newly added file
SPListItem listItem = file.ListItemAllFields;
//Assign values to the fields of newly added file
listItem["User_x0020_Name"] = userName;
listItem["Document_x0020_Type"] = documentType;
listItem["Check_x0020_Type"] = checkType;
//Update the list item with the newly added values to the fields
listItem.Update();
//Get the unique id of the newly added list item
documentGuid = listItem["UniqueId"].ToString();
}
}
The above code works fine. I have versioning enabled on my document library. When the above code run it creates two versions in document library. One when it upload document with
SPFile file = folder.Files.Add(saveFileWithName, fileContents, overWrite);
and another when it adds values to the column User_x0020_Name, Document_x0020_Type and
Check_x0020_Type using
listItem.Update();
I want to create only only one version when user upload document as well as add metadata. How to do this ? Can you please provide me any code or link through which I can resolve the above issue ?
Keep the code same just replace "listItem.Update();" with "listItem.SystemUpdate(false);" it will update the metadata and will not increase the version number.

Categories