How to upload a file in Sharepoint 2010 using c# console - c#

Is there a way to automatically upload a file in Sharepoint 2010 using c#? We have no administrative control on the Sharepoint server. We just need to write a program that will upload a local file to a designated sharepoint library. The program will run on our server which in no way affiliated with the sharepoint server.

The following options could be considered for uploading the file into SharePoint via CSOM.
Prerequisites: SharePoint Foundation 2010 Client Object Model Redistributable
Using FileCollection.Add method
FileCollection.Add method adds a file to the collection based on provided file creation information
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();
}
Usage
using (var ctx = new ClientContext(webUri))
{
ctx.Credentials = credentials;
UploadFile(ctx,"Documents/Orders",#"c:\upload\user guide.docx");
}
where Orders is a folder in Documents library
According to Uploading files using Client Object Model in SharePoint 2010:
The above code might fail throwing a (400) Bad Request error depending
on the file size.
Using File.SaveBinaryDirect method
File.SaveBinaryDirect method - uploads the specified file to a SharePoint site without requiring an ExecuteQuery() method call.
public static void UploadFile(ClientContext context, string folderUrl, string uploadFilePath)
{
using (var fs = new FileStream(uploadFilePath, FileMode.Open))
{
var fileName = Path.GetFileName(uploadFilePath);
var fileUrl = String.Format("{0}/{1}", folderUrl, fileName);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(context, fileUrl, fs, true);
}
}
Usage
using (var ctx = new ClientContext(webUri))
{
ctx.Credentials = credentials;
UploadFile(ctx,"/News/Documents/Orders",#"c:\upload\user guide.docx");
}
where Orders is a folder in Documents library located on web site News.
FolderUrl format: /<web url>/<list url>/<folder url>

Related

Examples how to save file from external .Net application to Sharepoint

I need to save files from the existing AngularJS/.NET application to Sharepoint. Most of the examples I see online is when applications reside on Sharepoint itself. How do I save files from outside?
I've been given a user access to our organization's Sharepoint site but no application user passwords. What do I need to request from administrators of SharePoint site to be able to write the code?
We can use CSOM C# code to upload file to SharePoint 2010 document library. We need use an admin user and password to pass the Credentials in the .NET application server.
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();
}
Usage
var siteUrl="http://sp2010";
var username="admin";
var password="xx";
var domainName="domain1";
using (var ctx = new ClientContext(webUri))
{
ctx.Credentials = new System.Net.NetworkCredential(username, password, domainName);
UploadFile(ctx,"Documents/folder1",#"c:\upload\test.docx");
}
The following article for your reference.
Uploading files using Client Object Model in SharePoint 2010

upload image to sharepoint generic list using csom C#

How I can upload image to a SharePoint List "custom List" not library using CSOM C#?
Here is what I have tried so far:
FieldUrlValue url = new FieldUrlValue();
url.Url = FileUpload.PostedFile.FileName;
url.Description = "Your description here";
newItem["Image"] = url;
You can use this code to upload documents into SharePoint via the CSOM:
using (ClientContext ctx = new ClientContext("http://urlToYourSiteCollection")) {
FileCreationInformation fci = new FileCreationInformation();
fci.Content = System.IO.File.ReadAllBytes("PathToSourceDocument");
fci.Url = System.IO.Path.GetFileName("PathToSourceDocument");
Web web = ctx.Web;
List targetDocLib = ctx.Web.Lists.GetByTitle("yourTargetLibrary");
ctx.ExecuteQuery();
Microsoft.SharePoint.Client.File newFile = targetDocLib.RootFolder.Files.Add(fci);
ctx.Load(newFile);
ctx.ExecuteQuery();
}
If you want to set properties of the new item, you can do it this way:
ListItem lItem = newFile.ListItemAllFields;
lItem.File.CheckOut(); //CHECK OUT VERY IMPORTANT TO CHANGE PROPS
ctx.ExecuteQuery();
lItem["yourProperty"] = "somewhat";
lItem.Update();
lItem.File.CheckIn("Z", CheckinType.OverwriteCheckIn);
ctx.ExecuteQuery();
If you need to upload files to a SharePoint site please visit the following link where it is explained how to read and upload files using CSOM
How to download/upload files from/to SharePoint 2013 using CSOM?

C# Google Drive APIv3 Upload File

I'm making a simple Application that Links to a Google Drive Account and then can Upload Files to any Directory and respond with a (direct) download Link.
I already got my User Credentials and DriveService objects, but I can't seem to find any good examples or Docs. on the APIv3.
As I'm not very familiar with OAuth, I'm asking for a nice and clear explanation on how to Upload a File with byte[] content now.
My Code for Linking the Application to a Google Drive Account: (Not sure if this works perfectly)
UserCredential credential;
string dir = Directory.GetCurrentDirectory();
string path = Path.Combine(dir, "credentials.json");
File.WriteAllBytes(path, Properties.Resources.GDJSON);
using(var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) {
string credPath = Path.Combine(dir, "privatecredentials.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Drive API service.
_service = new DriveService(new BaseClientService.Initializer() {
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
File.Delete(path);
My Code for Uploading so far: (Does not work obviously)
public void Upload(string name, byte[] content) {
Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();
body.Name = name;
body.Description = "My description";
body.MimeType = GetMimeType(name);
body.Parents = new List() { new ParentReference() { Id = _parent } };
System.IO.MemoryStream stream = new System.IO.MemoryStream(content);
try {
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
request.Upload();
return request.ResponseBody;
} catch(Exception) { }
}
Thanks!
Once you have enabled your Drive API, registered your project and obtained your credentials from the Developer Consol, you can use the following code for recieving the user's consent and obtaining an authenticated Drive Service
string[] scopes = new string[] { DriveService.Scope.Drive,
DriveService.Scope.DriveFile};
var clientId = "xxxxxx"; // From https://console.developers.google.com
var clientSecret = "xxxxxxx"; // From https://console.developers.google.com
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId,
ClientSecret = clientSecret},
scopes,
Environment.UserName,
CancellationToken.None,
new FileDataStore("MyAppsToken")).Result;
//Once consent is recieved, your token will be stored locally on the AppData directory, so that next time you wont be prompted for consent.
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "MyAppName",
});
service.HttpClient.Timeout = TimeSpan.FromMinutes(100);
//Long Operations like file uploads might timeout. 100 is just precautionary value, can be set to any reasonable value depending on what you use your service for.
Following is a working piece of code for uploading to Drive.
// _service: Valid, authenticated Drive service
// _uploadFile: Full path to the file to upload
// _parent: ID of the parent directory to which the file should be uploaded
public static Google.Apis.Drive.v2.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Uploaded with .NET!")
{
if (System.IO.File.Exists(_uploadFile))
{
File body = new File();
body.Title = System.IO.Path.GetFileName(_uploadFile);
body.Description = _descrp;
body.MimeType = GetMimeType(_uploadFile);
body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
request.Upload();
return request.ResponseBody;
}
catch(Exception e)
{
MessageBox.Show(e.Message,"Error Occured");
}
}
else
{
MessageBox.Show("The file does not exist.","404");
}
}
Here's the little function for determining the MimeType:
private static string GetMimeType(string fileName)
{
string mimeType = "application/unknown";
string ext = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
mimeType = regKey.GetValue("Content Type").ToString();
return mimeType;
}
Additionally, you can register for the ProgressChanged event and get the upload status.
request.ProgressChanged += UploadProgessEvent;
request.ChunkSize = FilesResource.InsertMediaUpload.MinimumChunkSize; // Minimum ChunkSize allowed by Google is 256*1024 bytes. ie 256KB.
And
private void UploadProgessEvent(Google.Apis.Upload.IUploadProgress obj)
{
label1.Text = ((obj.ByteSent*100)/TotalSize).ToString() + "%";
// do updation stuff
}
That's pretty much it on Uploading..
Source.
If you've followed Google Drive API's .NET Quickstart guide, then you probably remember during first launch, a web page from google drive was prompting for authorization grant to access google drive with "Read only" permission?
The default scope "DriveService.Scope.DriveReadonly" from the quickstart guide can't be used if you intend on uploading files.
This worked for me
Remove "Drive ProtoType" from Apps connected to your account
Create another set of credentials with a new application name eg "Drive API .NET Quickstart2" in API Manager
Request access with this scope "DriveService.Scope.DriveFile"
private static readonly string[] Scopes = { DriveService.Scope.DriveReadonly };
private static readonly string ApplicationName = "Drive API .NET Quickstart2";}
You should land on a new page from google drive requesting new grant
Drive Prototype would like to: View and manage Google Drive files and folders that you have opened or created with this app
After allowing access, your application should be able to upload.
i have the same problem on mine application winforms c# fw 4.0
i installed already google drive api v3 by nuget
and also created json file from googles api and inserted into project
request.ResponseBody == null???
anyone has a solution for it ?
thanks by advance
I think you're going in the right direction, just a bit unsure.
The main steps in using the Google Drive API for a C# (.NET) application are
Enable the Google Drive API in your Google Account
Install the Google Drive SDK for .NET framework using "NuGet" package manager. For this, in Visual Studio, go to Tools -> NuGet Package Manager -> Package Manager Console and then enter the following command
Install-Package Google.Apis.Drive.v3
Make sure you "use" all the packages/libraries in your application using the "using" statements at the top. For example,
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
The code you have written above seems correct to me (I have not hard tested it). But if you have trouble in uploading files with it, you can try different approaches by the links mentioned below.
The above steps are largely taken from Google Drive API's .NET Quickstart page.
Further, you can and should refer to Google's documentation for the Google Drive SDK for .NET framework.
I hope the above content helped you.

Download a file from a specific library in Sharepoint

I have a simple console application that upload a file from a local folder to a library in sharepoint, and also have a method that download that folder, but using the url that is activated manually in the web site. But I need to download the same file that I upload a second later, it is for a test, AND WHAT I NEED IS TO ACTIVATE THE "VIEW LINK" FOR DOWNLOAD LATER. Here is my upload method:
static void o365SaveBinaryDirect(ClientContext o365Context, string o365LibraryName, string o365FilePath, string o365FileName) {
Web o365Web = o365Context.Web;
if (!LibraryExist(o365Context, o365Web, o365LibraryName)) {
CreateLibrary(o365Context, o365Web, o365LibraryName);
}
using (FileStream o365FileStream = new FileStream(o365FilePath, FileMode.Open)) {
Microsoft.SharePoint.Client.File.SaveBinaryDirect(o365Context, string.Format("/{0}/{1}", o365LibraryName, o365FileName), o365FileStream, true);
}
}
Now I have this method that download:
private static void DownloadFile(string webUrl, ICredentials credentials, string fileRelativeUrl) {
using (var client = new WebClient()) {
client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
client.Headers.Add("User-Agent: Other");
client.Credentials = credentials;
client.DownloadFile(webUrl, fileRelativeUrl);
}
}
I need to generate the url for download the file later.
Some suggestions:
avoid generating file url based on library title since library url is
not the same as library title
since Microsoft.SharePoint.Client.File.SaveBinaryDirect method from CSOM
API is used for uploafding a file, consider to utilize Microsoft.SharePoint.Client.File.OpenBinaryDirect method for downloading a file
The following example demonstrates how to upload a file into a library and then downloading it:
var sourceFilePath = #"c:\in\UserGuide.pdf"; //local file path;
var listTitle = "Documents"; //target library;
var list = ctx.Web.Lists.GetByTitle(listTitle);
ctx.Load(list.RootFolder);
ctx.ExecuteQuery();
var targetFileUrl = string.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, Path.GetFileName(sourceFilePath));
//upload a file
using (var fs = new FileStream(sourceFilePath, FileMode.Open))
{
Microsoft.SharePoint.Client.File.SaveBinaryDirect(ctx, targetFileUrl, fs, true);
}
//download a file
var downloadPath = #"c:\out\";
var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, targetFileUrl);
var fileName = Path.Combine(downloadPath, Path.GetFileName(targetFileUrl));
using (var fileStream = System.IO.File.Create(fileName))
{
fileInfo.Stream.CopyTo(fileStream);
}

Server Version, Site, Web in ClientContext of SharePoint throws error

I'm new to sharepoint. Im trying to upload a file and add metadata to the file. Below is my code. I can see some internal exceptions are their while declaring ClientContext
Exception: clientContext.ServerVersion threw an exception of type PropertyOrFieldNotInitializedException
The same is happening for Site, Web.
using (ClientContext clientContext = new ClientContext(SPURL))
{
//ClientContext clientContext = new ClientContext(SPURL);
clientContext.Credentials = new System.Net.NetworkCredential(userName, password, domain);
Web web = clientContext.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(PPTPath);
newFile.Url = "F:\\log.txt";
List docs = web.Lists.GetByTitle("Test");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
clientContext.ExecuteQuery();
using (FileStream fileStream =
new FileStream(PPTPath, FileMode.Open))
ClientOM.File.SaveBinaryDirect(clientContext,
DocumentRepository + PPTfilename, fileStream, true);
}
the CSOM libraries expect you to tell them what you want to query from the SharePoint environment upon calling ExecuteQuery().
Therefor you need to tell the clientcontext object what you want to load.
For instance:
Web web = clientContext.Web; should be followed by clientContext.Load(web);
This is a simple example. For uploading files your best bet is making use of the File.SaveBinaryDirect function. An example on how to use it can be found elsewhere on stackoverflow.

Categories

Resources