Office 365 Sharepoint Upload Files to Documents Library - c#

I am trying to use the following code to add files to my document library on Sharepoint Office365 using web services.
public void SaveFileToSharePoint(string fileName)
{
try
{
var copyService = new Copy { Url = "https://mydomain.com/_vti_bin/copy.asmx", Credentials = new NetworkCredential("username", "password", "domain") };
var destURL = "https://mydomain.com/Shared%20Documents/" + Path.GetFileName(fileName);
string[] destinationUrl = { destURL };
CopyResult[] cResultArray;
var fFiledInfo = new FieldInformation { DisplayName = "Description", Type = FieldType.Text, Value = Path.GetFileName(fileName) };
FieldInformation[] fFiledInfoArray = {fFiledInfo};
var copyresult = copyService.CopyIntoItems(destURL, destinationUrl, fFiledInfoArray, File.ReadAllBytes(fileName), out cResultArray);
var b = copyresult;
}
catch (Exception ex)
{
}
}
I receive the error "Object Moved". The URL loads the WSDL in the browser though. If there is a better way to upload and get files from SharePoint on Office365 online I would entertain that as well. Thanks.

as the ASMX webservices are deprecated you should check out the "new" rest services of sharepoint. ON MSDN you find information about it
Or you can use the Client object model which would be my favorite way. The following example shows basic usage, to connect to SharePoint online check out the following link
using(ClientContext context = new ClientContext("http://yourURL"))
{
Web web = context.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(#"C:\myfile.txt");
newFile.Url = "file uploaded via client OM.txt";
List docs = web.Lists.GetByTitle("Documents");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
context.ExecuteQuery();
}

Using roqz suggestions above, here is the ultimate solution I came up with to place files in the SharePoint 2013 Office 365 document library and to retrieve them by name:
public void SaveFileToSharePoint(string fileName)
{
using (var context = new ClientContext("https://mydomain.com/"))
{
var passWord = new SecureString();
foreach (var c in "MyPassword") passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("me#mydomain.com", passWord);
var web = context.Web;
var newFile = new FileCreationInformation {Content = File.ReadAllBytes(fileName), Url = Path.GetFileName(fileName)};
var docs = web.Lists.GetByTitle("Documents");
docs.RootFolder.Folders.GetByUrl("Test").Files.Add(newFile);
context.ExecuteQuery();
}
}
public void GetFileFromSharePoint(string fileName, string savePath)
{
using (var context = new ClientContext("https://mydomain.com/"))
{
var passWord = new SecureString();
foreach (var c in "MyPassword") passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("me#mydomain.com", passWord);
var web = context.Web;
var myFile = web.Lists.GetByTitle("Documents").RootFolder.Folders.GetByUrl("Test").Files.GetByUrl(fileName);
context.Load(myFile);
context.ExecuteQuery();
using (var ffl = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, myFile.ServerRelativeUrl))
{
using (var destFile = File.OpenWrite(savePath + fileName))
{
var buffer = new byte[8*1024];
int len;
while ((len = ffl.Stream.Read(buffer, 0, buffer.Length)) > 0)
{
destFile.Write(buffer, 0, len);
}
}
}
}
}

Related

Getting exception during fileupload to sharepoint in C#

Please see the code below. This is my initialization:
string siteUrl = "https://(*company domain*).sharepoint.com/sites/BankGuaranteeManagement/";
string documentLibrary = "BG Docs";
string fileName = VIEWSTATE_MAIN_FILE_NAME;
string customerFolder = "Bank Guarantees";
string userNameSP = "bgmfileuser#company.com";
string passwordSP = "hs#29n#$";
This is the fileupload code:
#region ConnectToSharePoint
string serverRelativeURL = "";
var securePassword = new SecureString();
foreach (char c in Password)
{ securePassword.AppendChar(c); }
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
var onlineCredentials = new SharePointOnlineCredentials(Login, securePassword);
#endregion
#region Insert the data
using (ClientContext clientContext = new ClientContext(siteUrl))
{
clientContext.Credentials = onlineCredentials;
Web web = clientContext.Web;
List libraryList = clientContext.Web.Lists.GetByTitle("Documents");
Folder folder = libraryList.RootFolder;
clientContext.Load(folder, f => f.ServerRelativeUrl);
clientContext.ExecuteQuery();
serverRelativeURL = folder.ServerRelativeUrl;
System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, serverRelativeURL + "/" + System.IO.Path.GetFileName(filePath), fs, true);
}
#endregion
}
catch (Exception exp)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(exp.Message + Environment.NewLine + exp.StackTrace);
}
On clientContext.ExecuteQuery, I am getting the following error:
Exception
{"The sign-in name or password does not match one in the Microsoft account system."}
Some points worth mentioning:
The ID being used in credentials has MFA disabled.
The ID being used is part of the Active directory.
I can login into portal.office.com using the same ID and password. So, no issues there.
.Net version is 4.6
Latest Sharepoint dll is installed and added.
I went through all materials on internet but cannot figure this ont out. Any help will be useful. Thanks.

How to read the contents of a single file in SharePoint Online using C#

I have the following url which displays the metadata of the file when put in the browser but I want the actual file content.
https://mySite/_api/web/folders/getbyurl('Shared%20Documents')/folders/getbyurl('09.%20SharePoint%20Tutorials')/files/GetByUrl('SharePoint%20365%20Co-authoring%20excel%20files.docx')
I have tried doing the following but I just get a 400 error when trying to execute the query on line 4:
ClientContext clientContext = new ClientContext("mySite");
File f = clientContext.Web.Folders.GetByUrl("Shared Documents").Folders.GetByUrl("09. SharePoint Tutorials").Files.GetByUrl("SharePoint 365 Co-authoring excel files.docx");
clientContext.Load(f);
clientContext.ExecuteQuery();
FileInformation fileInformation = File.OpenBinaryDirect(clientContext, (string)f.ServerRelativeUrl);
using (System.IO.StreamReader sr = new System.IO.StreamReader(fileInformation.Stream))
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
The code below for your reference:
string targetSiteURL = #"https://xx.sharepoint.com/sites/lz";
var login = "lz#xxx.onmicrosoft.com";
var password = "xxx";
var securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
SharePointOnlineCredentials onlineCredentials = new SharePointOnlineCredentials(login, securePassword);
ClientContext ctx = new ClientContext(targetSiteURL);
ctx.Credentials = onlineCredentials;
var web = ctx.Web;
ctx.Load(web);
ctx.ExecuteQuery();
var filePath = web.ServerRelativeUrl + "/Shared%20Documents/09.%20SharePoint%20Tutorials/SharePoint%20365%20Co-authoring%20excel%20files.docx";
FileInformation fileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(ctx, filePath);
using (System.IO.StreamReader sr = new System.IO.StreamReader(fileInformation.Stream))
{
String line = sr.ReadToEnd();
Console.WriteLine(line);
}
Console.ReadKey();

Can not upload image to google cloud bucket using c# windows application

Hello I have created a windows application which uploads image from hdd to google cloud server.
My code was working perfectly but after changing bucket name it is not working.
My both buckets are in the same project and I have given OAuth 2.0 to my project.
even there is no error showing while processing. Please help me.
string bucketForImage = ConfigurationManager.AppSettings["BucketName"];
string projectName = ConfigurationManager.AppSettings["ProjectName"];
string Accountemail = ConfigurationManager.AppSettings["Email"];
var clientSecrets = new ClientSecrets();
clientSecrets.ClientId = ConfigurationManager.AppSettings["ClientId"];
clientSecrets.ClientSecret = ConfigurationManager.AppSettings["ClientSecret"];
string gcpPath = #"D:\mrunal\tst_mrunal.png";
var scopes = new[] { #"https://www.googleapis.com/auth/devstorage.full_control" };
var cts = new CancellationTokenSource();
var userCredential = await GoogleWebAuthorizationBroker.AuthorizeAsync(clientSecrets, scopes, Accountemail, cts.Token);
var service = new Google.Apis.Storage.v1.StorageService();
var bucketToUpload = bucketForImage;
var newObject = new Google.Apis.Storage.v1.Data.Object()
{
Bucket = bucketToUpload,
Name = "mrunal.png"
};
fileStream = new FileStream(gcpPath, FileMode.Open);
var uploadRequest = new Google.Apis.Storage.v1.ObjectsResource.InsertMediaUpload(service, newObject,
bucketToUpload, fileStream, "image/png");
uploadRequest.OauthToken = userCredential.Token.AccessToken;
await uploadRequest.UploadAsync();
//uploadRequest.UploadAsync();
if (fileStream != null)
{
fileStream.Dispose();
}
Did you try this same code for the older bucket and it worked? It seems to me that there is an issue with line of code, uploadRequest.OauthToken = userCredential.Token.AccessToken. You are calling the Token.AccessToken directly from the userCredentials. These methods should be called from the userCredentials.Result.

Google Contacts access with Service Account json c#

I'm trying to access my Google Contacts using OAuth 2.0 for Server to Server Applications in a ASP.net MVC application but I'm having some troubles trying to retrieve the token. "test-470272c3a5fa.json" is the file I downloaded from google api console and is currently on my desktop. Any idea?
Here is my code:
public class GoogleContactsApiInterface
{
public GoogleContactsApiInterface()
{
ServiceAccountCredential serviceAccountCredential;
string[] scopes = { "https://www.google.com/m8/feeds/" };
string keyPath = "C:\\Users\\55122545\\Desktop\\test-470272c3a5fa.json";
using (var stream = new FileStream(keyPath, FileMode.Open, FileAccess.Read))
{
serviceAccountCredential = GoogleCredential.FromStream(stream)
.CreateScoped(scopes)
.UnderlyingCredential as ServiceAccountCredential;
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.AccessToken = serviceAccountCredential.Token.AccessToken;
parameters.RefreshToken = serviceAccountCredential.Token.RefreshToken;
RequestSettings rs = new RequestSettings("testApp", parameters);
rs.AutoPaging = true;
ContactsRequest cr = new ContactsRequest(rs);
Feed<Contact> f = cr.GetContacts();
foreach (Contact c in f.Entries)
{
//do something
}
}
}
}

Upload File To SharePoint Online(office 365) Library Invokes Error

How can one resolve this runtime error?
Error
Could not load file or assembly 'Microsoft.SharePoint.Library, Version = 14.0.0.0, Culture = neutral, PublicKeyToken = 71e9bce111e9429c' or one of its dependencies. The system can not find the file specified.
CODE
string destUrl = "URL";
string destFileUrl = destUrl + "biblioteca" + "/text.txt";
using(SPWeb site = new SPSite(destUrl).OpenWeb())
{
site.AllowUnsafeUpdates = true;
FileStream fileStream = File.Open("FILE" , FileMode.Open);
site.Files.Add(destFileUrl, fileStream, true/*overwrite*/);
fileStream.Close();
}
This works for me.
using (ClientContext clientContext = new ClientContext("SHAREPOINT URL")) {
SecureString passWord = new SecureString();
foreach (char c in "PASSWORD".ToCharArray()) passWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials("ACOUNT.onmicrosoft.com", passWord);
Web web = clientContext.Web;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(FILE);
newFile.Url = NAMEFORTHEFILE;
List docs = web.Lists.GetByTitle("LIBRARY NAME");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
clientContext.ExecuteQuery();
}
string fileName = #"C:\AddUser.aspx";
using (var context = new ClientContext("https://yourdomain.com")) {
var passWord = new SecureString();
foreach (var c in "YourPassword") passWord.AppendChar(c);
context.Credentials = new SharePointOnlineCredentials("YourUsername", passWord);
var web = context.Web;
var newFile = new FileCreationInformation {
Content = System.IO.File.ReadAllBytes(fileName),
Url = Path.GetFileName(fileName)
};
var docs = web.Lists.GetByTitle("Pages");
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
context.ExecuteQuery();
}
Have you encountered this error: The partner returned a bad sign-in name or password error. For more information, see Federation Error-handling Scenarios.
I have the following codes:
NetworkCredential Cred = new NetworkCredential(ConfigurationManager.AppSettings["Username"], ConfigurationManager.AppSettings["Password"], ConfigurationManager.AppSettings["Domain"]);
SecureString PassWord = new SecureString();
foreach (char c in ConfigurationManager.AppSettings["Password"].ToCharArray()) PassWord.AppendChar(c);
clientContext.Credentials = new SharePointOnlineCredentials(ConfigurationManager.AppSettings["Username"], PassWord);
Web web = clientContext.Web;
clientContext.Load(web);
You cannot use the server side object model to upload files to SharePoint Online.
One has to use the Client Object Model to upload files to SharePoint online.
More Info
Office 365 Sharepoint Upload Files to Documents Library

Categories

Resources