Uploading a file to sharepoint without a password - c#

i am trying to upload a file to sharepoint with c# using the microsoft sharepoint client
i have no issues when i create my context and give it my username and password like this
using (ClientContext ctx = new ClientContext(spSite))
{
if (!System.IO.File.Exists(fileLocation))
throw new FileNotFoundException("File not found.", fileLocation);
var credentials = new NetworkCredential("username", "password");
ctx.Credentials = credentials;
Web web = ctx.Web;
ctx.Load(user);
ctx.ExecuteQuery();
String fileName = System.IO.Path.GetFileName(fileLocation);
FileStream fileStream = System.IO.File.OpenRead(fileLocation);
ctx.Load(web.Folders);
ctx.ExecuteQuery();
Folder spFolder = web.Folders.FirstOrDefault(x => x.Name.Equals(spListCleanName));
FileCreationInformation fci = new FileCreationInformation();
fci.Url = spSite + spLibraryName + file;
byte[] bytes = System.IO.File.ReadAllBytes(fileLocation);
fci.Content = bytes;
Microsoft.SharePoint.Client.File spFile = spFolder.Files.Add(fci);
spFile.ListItemAllFields.Update();
ctx.ExecuteQuery();
}
but my issue comes in the network credentials part. is there a way to use the current users credentials (through iis or .net or anything) so that i don't have to ask for their password? since that isn't something we want to save in plain text anywhere.
thank you in advance

Use the CredentialCache.DefaultCredentials (https://msdn.microsoft.com/en-us/library/system.net.credentialcache.defaultcredentials(v=vs.110).aspx) instead of NetworkCredential object.
This will use the users security context.

Related

How to copy a file to a sharepoint site

I have to copy a file on a sharepoint site.
I have seen that the only authentication working is with the AuthenticationManager.
So this works:
var authManager = new AuthenticationManager();
var ctx = authManager.GetWebLoginClientContext(strHexagon);
Web web = ctx.Web;
User user = web.CurrentUser;
ctx.Load(web);
ctx.Load(user);
ctx.ExecuteQuery();
lbxInfo.Items.Add(web.Title);
lbxInfo.Items.Add(user.LoginName);
Now, after having authenticated I need to copy a file to the sharepoint site.
I have seen that there is ctx.Web.SaveFileToLocal but what if I have to copy from local to sharepoint?
Thanks
You can use the OfficeDevPnP.Core library
string str1_Url=... <--- sharepoint site
string str2_FileSource_Full= #"C:\temp\A.txt";
string str3_FileDestination_NameExt="B.txt";
string str4_TopDestination_Folder=... <--- sharepoint site title folder
string str5_TopDestination_SubFolder=... <--- folder e.g. Production
string str6_TopDestination_AllSubFolders=...<--- subfolder e.g. Test
// AuthenticationManager -> ByPasses Multi-Factor Authentication
var authManager = new AuthenticationManager();
var ctx = authManager.GetWebLoginClientContext(str1_Url);
// Web & User definitions
Web web = ctx.Web;
User user = web.CurrentUser;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(str2_FileSource_Full);
// Rename the destination file
newFile.Url = str3_FileDestination_NameExt;
Microsoft.SharePoint.Client.List docs = web.Lists.GetByTitle(str4_TopDestination_Folder);
// Selects a Folder inside the root one
Microsoft.SharePoint.Client.Folder folder = docs.RootFolder.Folders.GetByUrl(str5_TopDestination_SubFolder);
folder.Folders.Add(str6_TopDestination_AllSubFolders);
var targetFolder = folder.Folders.GetByUrl(str6_TopDestination_AllSubFolders);
// Uploads a file to the targetFolder
newFile.Overwrite = true;
Microsoft.SharePoint.Client.File uploadFile = targetFolder.Files.Add(newFile);
// Executes query
ctx.Load(docs);
ctx.Load(uploadFile);
ctx.Load(web);
ctx.Load(user);
ctx.ExecuteQuery();

Recursive upload to FTP server in C#

I would need to upload a folder (which contains sub folders and files) from one server to another from C# code. I have done few research and found that we can achieve this using FTP. But with that I am able to move only files and not the entire folder. Any help here is appreciated.
The FtpWebRequest (nor any other FTP client in .NET framework) indeed does not have any explicit support for recursive file operations (including uploads). You have to implement the recursion yourself:
List the local directory
Iterate the entries, uploading files and recursing into subdirectories (listing them again, etc.)
void UploadFtpDirectory(
string sourcePath, string url, NetworkCredential credentials)
{
IEnumerable<string> files = Directory.EnumerateFiles(sourcePath);
foreach (string file in files)
{
using (WebClient client = new WebClient())
{
Console.WriteLine($"Uploading {file}");
client.Credentials = credentials;
client.UploadFile(url + Path.GetFileName(file), file);
}
}
IEnumerable<string> directories = Directory.EnumerateDirectories(sourcePath);
foreach (string directory in directories)
{
string name = Path.GetFileName(directory);
string directoryUrl = url + name;
try
{
Console.WriteLine($"Creating {name}");
FtpWebRequest requestDir =
(FtpWebRequest)WebRequest.Create(directoryUrl);
requestDir.Method = WebRequestMethods.Ftp.MakeDirectory;
requestDir.Credentials = credentials;
requestDir.GetResponse().Close();
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode ==
FtpStatusCode.ActionNotTakenFileUnavailable)
{
// probably exists already
}
else
{
throw;
}
}
UploadFtpDirectory(directory, directoryUrl + "/", credentials);
}
}
For the background of complicated code around creating the folders, see:
How to check if an FTP directory exists
Use the function like:
string sourcePath = #"C:\source\local\path";
// root path must exist
string url = "ftp://ftp.example.com/target/remote/path/";
NetworkCredential credentials = new NetworkCredential("username", "password");
UploadFtpDirectory(sourcePath, url, credentials);
A simpler variant, if you do not need a recursive upload:
Upload directory of files to FTP server using WebClient
Or use FTP library that can do the recursion on its own.
For example with WinSCP .NET assembly you can upload whole directory with a single call to the Session.PutFilesToDirectory:
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "ftp.example.com",
UserName = "username",
Password = "password",
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Download files
session.PutFilesToDirectory(
#"C:\source\local\path", "/target/remote/path").Check();
}
The Session.PutFilesToDirectory method is recursive by default.
(I'm the author of WinSCP)

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?

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