c# Upload File to SharePoint Document Library - c#

My requirement is the following:
I have various bits of network hardware, from which we regularly export configurations (this is done using another c#/.NET app I created, this works really well - the tool logs in via SSH to the various devices and downloads the latest configuration to the local hard disk of the server from which the app runs).
We have various SharePoint online sites (provided via our M365 subscription).
I want to have these configs uploaded to a particular folder, in a particular document library, in a particular SharePoint Online site, basically so that there is an off-site backup of the config files.
I was following the steps in this blog: https://daoudisamir.com/from-c-to-sharepoint-file-upload-using-csom-with-subfolders-structure/.
It looked like it did what I wanted... but when I try to build the code, it tells me that I'm missing references to assemblies etc. I know that this means that I'm missing "using" directives, but I've tried all sorts of variations to reference the various NUGET packages that are instructed to be installed, but I can't get this to work and couldn't see anywhere on the blog itself to email the owner.
Anyone got any ideas... at the moment, my code is more or less a copy/paste of what's on the blog page, but I've included my code here for convenience:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Security;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
namespace UploadToSharePoint_Net48
{
internal class Program
{
static void Main(string[] args)
{
string SiteUrl = "https://You.sharepoint.com/sites/Upload";
string DocumentLibrary = "UploadLibrary";
string FileName = #"C:\testupload.pdf";
string CustomerFolder = "1564_dsfgsst";
string UserName = "samir.daoudi#******.co.uk";
string Password = "*****";
UploadFileToSharePoint(SiteUrl, DocumentLibrary, CustomerFolder, FileName, UserName, Password);
}
private static void UploadFileToSharePoint(string SiteUrl, string DocLibrary, string ClientSubFolder, string FileName, string Login, string Password)
{
try
{
#region ConnectToSharePoint
var securePassword = new SecureString();
foreach (char c in Password)
{ securePassword.AppendChar(c); }
var onlineCredentials = new SP.SharePointOnlineCredentials(Login, securePassword);
#endregion
#region Insert the data
using (SP.ClientContext CContext = new SP.ClientContext(SiteUrl))
{
CContext.Credentials = onlineCredentials;
SP.Web web = CContext.Web;
SP.FileCreationInformation newFile = new SP.FileCreationInformation();
byte[] FileContent = System.IO.File.ReadAllBytes(FileName);
newFile.ContentStream = new MemoryStream(FileContent);
newFile.Url = Path.GetFileName(FileName);
SP.List DocumentLibrary = web.Lists.GetByTitle(DocLibrary);
//SP.Folder folder = DocumentLibrary.RootFolder.Folders.GetByUrl(ClientSubFolder);
SP.Folder Clientfolder = DocumentLibrary.RootFolder.Folders.Add(ClientSubFolder);
Clientfolder.Update();
SP.File uploadFile = Clientfolder.Files.Add(newFile);
CContext.Load(DocumentLibrary);
CContext.Load(uploadFile);
CContext.ExecuteQuery();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("The File has been uploaded" + Environment.NewLine + "FileUrl -->" + SiteUrl + "/" + DocLibrary + "/" + ClientSubFolder + "/" + Path.GetFileName(FileName));
}
#endregion
}
catch (Exception exp)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(exp.Message + Environment.NewLine + exp.StackTrace);
}
finally
{
Console.ReadLine();
}
}
}
}
The errors are with all the references to SP.xxxxx
I can see that there is no definition for anything called "SP", but I'm assuming at this stage that this is in one of the external libraries or whatever is in the NUGETS that are required.
Any help gratefully received.
Thanks
Colin

Related

C# Console app need assistance with main args error

I have the following c# Console app I would run this in ssis but i am using a couple of PDF manipulating librarys. so i am going to call an exe from my ssis package while passing in a file path.
But i am getting the following error when trying to run via the exe.
Unhandled Exception: System.IndexOutOfRangeException: Index was
outside the bounds of the array. at ConsoleApp.program.Main(String[]
args) line 87
BUT if i run in debug it works fine. Once i get it working on its own via the exe, i want to pass the filepath as a parameter in ssis.
see c# below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.util;
using System.IO;
namespace PDF_Read_ConsoleApp
{
class Program
{
public static void FilePath(string path)
{
//Console.WriteLine("Please enter full pdf path \n\n ");
//path = Console.ReadLine();
string fp;
fp = #path;
string[] files = Directory.GetFiles(path, "*.pdf");
foreach (string s in files)
{
string txtOutput = s.Replace(".pdf", ".txt");
if (File.Exists(txtOutput))
{
File.Delete(txtOutput);
}
string output;
PDDocument doc = null;
try
{
doc = PDDocument.load(s);
PDFTextStripper stripper = new PDFTextStripper();
stripper.getText(doc);
output = stripper.getText(doc);
StreamWriter NewFile;
NewFile = new StreamWriter(txtOutput);
//NewFile.Write(output.ToString());
NewFile.Write(output.ToString());
NewFile.Close();
}
finally
{
//if (doc != null)
//{
doc.close();
// Console.WriteLine("\n\n File saveed - ({0} ", txtOutput);
//}
}
}
}
static void Main(string[] args)
{
args[0] = #"C:\SSIS_Packages\PDF_Import\PDF_Import\PO_pdfs"; //// TESTING FILE PATH1
FilePath(args[0]);
}
}
}
Kind Regards
Rob
I have managed to get it working, I need to enter an argument within the debug screen, see information in URL below
Console app arguments, how arguments are passed to Main method
THank you for everyone's comments

Vs.Net C# Azure flle storage fails to add File for existing File Share

VS.NET C# fails to create file on Azure File Storage for Existing File share
I'm using Microsoft.WindowsAzure.Storage lib to access Azure File Storage API. My method creates File Share and uploads file. It works when File Share is created, but skips file upload when File Share exists.
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
public void SaveText( string fileName )
{
string accountName = "mylogs";
string key = #"dvjdjhsvdjfhvsjhdvfjhsvdfjhC2g==";
var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
var share = storageAccount.CreateCloudFileClient().GetShareReference("test");
share.CreateIfNotExistsAsync().Wait();
var root = share.GetRootDirectoryReference();
root.GetFileReference(fileName).UploadTextAsync("mytext").Wait();
}
First SaveText(file1) call works fine, Share & "file1" got created.
Second SaveText(file2) call, no errors, no "file2" created.
Same user, same app.
I'm using the nuget package WindowsAzure.Storage, version 9.3.3, and with a console project(not .net core), it works fine.
Sample code as blow(just use yours):
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using System;
namespace AzureFileTest
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.SaveText("file1"); //in the first call, file1 created and text uploads.
p.SaveText("file2"); //in the second call, file2 created and text uploads.
Console.WriteLine("done now");
Console.ReadLine();
}
public void SaveText(string fileName)
{
string accountName = "xxxxx";
string key = "xxxxxx";
var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, key), true);
var share = storageAccount.CreateCloudFileClient().GetShareReference("test");
share.CreateIfNotExistsAsync().Wait();
var root = share.GetRootDirectoryReference();
root.GetFileReference(fileName).UploadTextAsync("mytext").Wait();
}
}
}
Please let me know if any more issues, or any difference between the codes.

How to get Monotorrents DHT to work?

Iam trying to get the dht implementation of monotorrent to work but i just cant seem to find any peers.
ive tried most of the examplecode code availeble on the net like the testclient and dhttest.
I have tried with several diffrent infohashes.
Anyone here got it working? or do you know where i can find the devs?
This is how my code looks atm:
using System;
using System.Collections.Generic;
using System.Text;
using MonoTorrent.Dht;
using MonoTorrent.Dht.Listeners;
using System.Net;
using System.IO;
using MonoTorrent.Common;
using MonoTorrent.Tracker.Listeners;
namespace SampleClient
{
class Program
{
static void Main(string[] args)
{
string basePath = Environment.CurrentDirectory;
string torrentsPath = Path.Combine(basePath, "Torrents");
Torrent torrent = null;
// If the torrentsPath does not exist, we want to create it
if (!Directory.Exists(torrentsPath))
Directory.CreateDirectory(torrentsPath);
// For each file in the torrents path that is a .torrent file, load it into the engine.
foreach (string file in Directory.GetFiles(torrentsPath))
{
if (file.EndsWith(".torrent"))
{
try
{
// Load the .torrent from the file into a Torrent instance
// You can use this to do preprocessing should you need to
torrent = Torrent.Load(file);
Console.WriteLine(torrent.InfoHash.ToString());
}
catch (Exception e)
{
Console.Write("Couldn't decode {0}: ", file);
Console.WriteLine(e.Message);
continue;
}
}
}
DhtListener listener = new DhtListener(new IPEndPoint(IPAddress.Parse("192.168.2.3"), 10000));
DhtEngine engine = new DhtEngine(listener);
//engine.RegisterDht(dht);
byte[] nodes = null;
if (File.Exists("mynodes"))
nodes = File.ReadAllBytes("mynodes");
listener.Start();
int i = 0;
bool running = true;
StringBuilder sb = new StringBuilder(1024);
while (running)
{
engine.Start(nodes);
while (Console.ReadLine() != "q")
{
engine.GetPeers(torrent.InfoHash);
}
File.WriteAllBytes("mynodes", engine.SaveNodes());
}
}
}
}
I know it's very old question, I'm not sure why it's still noone has answer it, anyway. The problem seem to be this line:
DhtListener listener = new DhtListener(new IPEndPoint(IPAddress.Parse("192.168.2.3"), 10000));
This ip is not the real ip, so you actually asl peers to send the respone to unkonw adress.
What to do? register your own adress.

Console Application to mount azure cloud drive

I want to mount vhd from my private container. After google I get that it is only possible through .net. I am more of a JAVA person. I need a batch script or code in c# (So that I can get an exe file) which can automatically run at startup and mount vhd. So I decided to create a console app in order to get exe file.(I have very less knowledge c#/Visual studio) I am using following C# console application to do this.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.Internal;
namespace WorkerRole1
{
public class WorkerRole : RoleEntryPoint
{
public override void Run()
{
// This is a sample worker implementation. Replace with your logic.
Trace.WriteLine("WorkerRole1 entry point called", "Starting");
MountDrive();
//while (true)
//{
// Thread.Sleep(10000);
// Trace.WriteLine("Working", "Information");
//}
}
public override bool OnStart()
{
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
// For information on handling configuration changes
// see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.
return base.OnStart();
}
public void MountDrive()
{
string connectionStringSettingName = "DefaultEndpointsProtocol=http;AccountName=abc;AccountKey=xyz";
string azureContainerName = "vhds";
string vhdName = "myvhd.vhd";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionStringSettingName);
//CloudStorageAccount storageAccount = CloudStorageAccount.DevelopmentStorageAccount;
LocalResource localCache = RoleEnvironment.GetLocalResource("MyAzureDriveCache");
CloudDrive.InitializeCache(localCache.RootPath, localCache.MaximumSizeInMegabytes);
Trace.WriteLine("RootPath =====" + localCache.RootPath);
Trace.WriteLine("MaximumSizeInMegabytes =====" + localCache.MaximumSizeInMegabytes);
// Just checking: make sure the container exists
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
blobClient.GetContainerReference(azureContainerName).CreateIfNotExist();
// Create cloud drive
CloudDrive myCloudDrive = storageAccount.CreateCloudDrive(
blobClient
.GetContainerReference(azureContainerName)
.GetPageBlobReference(vhdName)
.Uri.ToString()
);
Trace.WriteLine("Uri =====" + blobClient
.GetContainerReference(azureContainerName)
.GetPageBlobReference(vhdName)
.Uri.ToString());
try
{
myCloudDrive.Create(1024);
}
catch (CloudDriveException ex)
{
// handle exception here
// exception is also thrown if all is well but the drive already exists
}
string driveLetter = myCloudDrive.Mount(50, DriveMountOptions.Force);//Here It throws a Exception
Trace.WriteLine("Drive =====" + driveLetter);
for (int i = 0; i < 10; i++)
{
System.IO.File.WriteAllText(driveLetter + "\\" + i.ToString() + ".txt", "Test");
}
}
}
}
But I keep getting exception ERROR_DEVFABRIC_LOCAL_MOUNT_ONLY at
string driveLetter = myCloudDrive.Mount(50, DriveMountOptions.Force);
Please tell me where am I going wrong?
When RoleEnvironment.IsAvailable is set to false, this means you are not running in a Windows Azure Web/Worker/VM Role. The Windows Azure Drive only works when mounted in these roles (since it depends on RoleEnvironment).
More information can be found in the whitepaper.
ERROR_DEVFABRIC_LOCAL_MOUNT_ONLY means that when you are running locally you must mount the drive form development storage.
change the following line:
string connectionStringSettingName = "UseDevelopmentStorage=true";
or even better use RoleEnvironment.GetConfigurationSettingValue, like:
string connectionStringSettingName = RoleEnvironment.GetConfigurationSettingValue("DriveConnectionString");
and set the Setting in the service configuration (files)

How do I restore a file from the recycle bin using C#?

Moving files to the recycle bin and emptying the recycle bin are well documented, but how can a file be programmatically restored from the recycle bin?
There seems not to be a solution in pure C#. You most likely have to resort to P/Invoke.
This article presents a solution in C++ using the SHFileOperation API.
The only other reference to this beyond the previously mentioned link to codeproject that I can see mentions this:
Call SHGetFolderLocation passing CSIDL_BITBUCKET.
Then you can manipulate that folder as usual.
You'll have to create an interop for the SHGetFolderLocation function.
CSIDL_BITBUCKET being the CSIDL ("constant special item ID list") value for the virtual Recycle Bin folder. The quote is taken from here, and will involve interop with the Windows shell. MSDN also mentions that this function has been deprecated in favour of another in Vista.
Hope below code will work to restore the files. Please make sure, STA Calls only supported for shell calls
using System;
using System.Collections;
using System.Windows.Forms;
using System.IO;
using Shell32; //Reference Microsoft Shell Controls And Automation on the COM tab.
using System.Runtime.InteropServices;
using Microsoft.VisualBasic.FileIO;
using System.Threading;
private static void Restore(object param)
{
object[] args = (object[])param;
string filename = (string)args[0];
string filepath = (string)args[1];
Shl = new Shell();
Folder Recycler = Shl.NameSpace(10);
var c = Recycler.Items().Count;
var _recycler = Recycler.Items();
for (int i = 0; i < _recycler.Count; i++)
{
FolderItem FI = _recycler.Item(i);
string FileName = Recycler.GetDetailsOf(FI, 0);
if (Path.GetExtension(FileName) == "") FileName += Path.GetExtension(FI.Path);
//Necessary for systems with hidden file extensions.
string FilePath = Recycler.GetDetailsOf(FI, 1);
if (filepath == Path.Combine(FilePath, FileName))
{
DoVerb(FI, "ESTORE");
break;
}
}
}
private static bool DoVerb(FolderItem Item, string Verb)
{
foreach (FolderItemVerb FIVerb in Item.Verbs())
{
if (FIVerb.Name.ToUpper().Contains(Verb.ToUpper()))
{
FIVerb.DoIt();
return true;
}
}
return false;
}

Categories

Resources