Get all documents from a sharepoint document library - c#

I want to retrieve all documents from an SPDocumentLibrary I've tried this way but then I got stucked
using (SPSite mysite = SPContext.Current.Site)
{
using (SPWeb myweb = mysite.OpenWeb())
{
SPDocumentLibrary myDocLib = (SPDocumentLibrary)myweb.Lists["DocLibrary"];
SPList myList = SPContext.Current.List;
SPFileCollection myFiles = myList.;
foreach (SPListItem myItem in myList.Items)
{
//adding each found file to my SPFileCollection
myFiles.Add(myItem.File);
}
}
}
but the SPFileCollection.Add function takes more than the file argument !

Once Again
link here
public static bool getAllDocuments()
{
Console.WriteLine("getAllDocuments debug, START");
bool isOK = false;
string baseUrl = "http://jabdw3421:82/sites/TestSite/";
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(baseUrl))
{
using (SPWeb web = site.OpenWeb())
{
SPDocumentLibrary lib = (SPDocumentLibrary)web.Lists["TestLib"];
IEnumerable<SPFile> allFiles = ExploreFolder(lib.RootFolder);
foreach (SPFile file in allFiles)
{
Console.WriteLine("getAllDocuments debug, File Name : " + file.Name);
Console.WriteLine("getAllDocuments debug, File CharSetName : " + file.CharSetName);
Console.WriteLine("getAllDocuments debug, File SourceLeafName : " + file.SourceLeafName);
}
}
}
});
}
catch (Exception e)
{
Console.WriteLine("getAllDocuments debug, " + e.Message);
isOK = false;
}
Console.WriteLine("getAllDocuments debug, END");
return isOK;
}
private static IEnumerable<SPFile> ExploreFolder(SPFolder folder)
{
foreach (SPFile file in folder.Files)
{
yield return file;
}
foreach (SPFolder subFolder in folder.SubFolders)
{
foreach (SPFile file in ExploreFolder(subFolder))
{
yield return file;
}
}
}

If I had to guess: you don't actually want to add them to a SPFileCollection. Doing this means that you're copying the files, but without using the convenient Copy method.
You probably just want to store them temporarily in a List<SPFile> or similar.
There are a lot of classes in the SharePoint object library called Collections, but they are not meant to be used like classes in the Systems.Collections namespace.

Related

Unable to change some js/html file content on container start. getting access denied exception

I have a case where i need to inject some Envrionment variable values in compiled vuejs js/html file which resides inisde my .net core 3.1 application.
I have put the content changing logic on startup.cs in Configure method.
I am getting Access denied exception
My code is
private void ReplaceEnvironmentVariableWithVal()
{
try
{
string apiurlToken = "VUE_APP_BEAPI_URL";
string relevantPath = "VUE_APP_RELEVANTPATH";
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "clientapp", "dist", "js");
Console.WriteLine($"{apiurlToken} env value is {GetEnvVariable(apiurlToken)}");
Console.WriteLine($"{relevantPath} env value is {GetEnvVariable(relevantPath)}");
Console.WriteLine("Application Root Path of js files " + path);
DirectoryInfo dir = new DirectoryInfo(path);
Dictionary<string, string> dict = new Dictionary<string, string>();
if (dir != null)
{
foreach (var file in dir.GetFiles())
{
if (file.Extension == "js" || file.Extension == ".js")
{
var fileContent = File.ReadAllText(file.FullName);
if (!String.IsNullOrWhiteSpace(fileContent))
{
if (fileContent.Contains(apiurlToken))
{
string variableValue = GetEnvVariable(apiurlToken);
if (!String.IsNullOrWhiteSpace(variableValue))
{
fileContent = fileContent.Replace(apiurlToken, variableValue);
dict[file.FullName] = fileContent;
}
}
if (fileContent.Contains(relevantPath))
{
string variableValue = GetEnvVariable(relevantPath);
//if (!String.IsNullOrWhiteSpace(variableValue))
{
fileContent = fileContent.Replace(relevantPath, variableValue);
dict[file.FullName] = fileContent;
}
}
}
}
}
}
else
{
Console.WriteLine("Application Root Path of js files not exists");
}
foreach (KeyValuePair<string, string> entry in dict)
{
Console.WriteLine("Updating " + entry.Key);
using (var fs = new FileStream(entry.Key, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))
{
using var sr = new StreamWriter(fs);
sr.Write(entry.Value);
}
Console.WriteLine("Update Completed " + entry.Key);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception in ReplaceEnvironmentVariableWithVal:" + ex.Message);
}
}
I have achieve the writing of files my giving the user right's. i have log the user under which application was running and it was default.
then added following line in my docker file
COPY --chown=default:default . .
which basically given right's to the user

C# System.IO.IOException

I have following code:
using System;
using System.Collections.Generic;
using System.IO;
using VirusTotalNET;
using VirusTotalNET.Objects;
using System.Linq;
using System.Security.Permissions;
namespace VirusTotalNETClient
{
class Program
{
private const string ScanUrl = "http://www.google.com/";
static void Main(string[] args)
{
VirusTotal virusTotal = new VirusTotal("5d8684f50946c2bdeaf5c4fd966f61f3661de808e9d7324b99788d6f4fb7ad57");
//Use HTTPS instead of HTTP
virusTotal.UseTLS = true;
//creating folder for programs reliqies and output log
string folderName = "C:\\OnlineScanner";
System.IO.Directory.CreateDirectory(folderName);
//get list of files to analyse
var paths = Traverse("C:\test");
File.WriteAllLines("C:\\OnlineScanner\\test.txt", paths);
foreach (string line in File.ReadLines("C:\\test.txt"))
{
//Define what file you want to analyse
FileInfo fileInfo = new FileInfo(line);
//Check if the file has been scanned before.
FileReport fileReport = virusTotal.GetFileReport(fileInfo);
bool hasFileBeenScannedBefore = fileReport.ResponseCode == ReportResponseCode.Present;
//If the file has been scanned before, the results are embedded inside the report.
if (hasFileBeenScannedBefore)
{
int detekce = fileReport.Positives;
if (detekce >= 1)
{
using (var writer = new StreamWriter("C:\\OnlineScanner\\OnlineScannerLog.txt"))
{
writer.WriteLine(line);
writer.WriteLine("URL to test: " + fileReport.Permalink);
writer.WriteLine("Detect ratio: " + fileReport.Positives + "/54");
writer.WriteLine("Message: " + fileReport.VerboseMsg);
writer.WriteLine();
writer.WriteLine();
}
}
System.Threading.Thread.Sleep(16000);
}
else
{
ScanResult fileResult = virusTotal.ScanFile(fileInfo);
int detekce = fileReport.Positives;
if (detekce >= 1)
{
using (var writer = new StreamWriter("C:\\OnlineScanner\\OnlineScannerLog.txt"))
{
writer.WriteLine(line);
writer.WriteLine("URL to test: " + fileReport.Permalink);
writer.WriteLine("Detect ratio: " + fileReport.Positives + "/54");
writer.WriteLine("Message: " + fileReport.VerboseMsg);
writer.WriteLine();
writer.WriteLine();
}
}
System.Threading.Thread.Sleep(16000);
}
}
}
private static IEnumerable<string> Traverse(string rootDirectory)
{
IEnumerable<string> files = Enumerable.Empty<string>();
IEnumerable<string> directories = Enumerable.Empty<string>();
try
{
// The test for UnauthorizedAccessException.
var permission = new FileIOPermission(FileIOPermissionAccess.PathDiscovery, rootDirectory);
permission.Demand();
files = Directory.GetFiles(rootDirectory);
directories = Directory.GetDirectories(rootDirectory);
}
catch
{
// Ignore folder (access denied).
rootDirectory = null;
}
foreach (var file in files)
{
yield return file;
}
// Recursive call for SelectMany.
var subdirectoryItems = directories.SelectMany(Traverse);
foreach (var result in subdirectoryItems)
{
yield return result;
}
}
}
}
This code run some time (arround 15secs) but then program crashs.
The error is
System.IO.IOException, process can't access to file C:\hiberfil.sys.
http://upnisito.cz/images/2016_12/319crasherrror.png
Do you have any idea how to solve it?

Upload file to folder or subfolder on Sharepoint

Im trying to create a method to upload a file stream to a sharepoint so far i have this
public static void SPUploadFileStream(string username, string filePath, Stream fileData)
{
//string siteUrl = Configuration.SPSiteURL;
string siteUrl = SPContext.Current.Web.Url;
SPUser currentUser = SPUtils.GetCurrentUser(username);
if (currentUser == null)
{
throw new SPGappUnknownUserException(username);
}
using (SPSite site = new SPSite(siteUrl, currentUser.UserToken))
{
using (SPWeb web = site.OpenWeb())
{
bool allowWebUnsafeUpdt = web.AllowUnsafeUpdates;
if (!allowWebUnsafeUpdt)
web.AllowUnsafeUpdates = true;
try
{
SPCreateFolder(Path.GetDirectoryName(filePath), username);
SPFile newFile = web.Files.Add(filePath, fileData, true); //true = replace
}
catch (Exception ex)
{
LoggingService.LogError(ex);
//site.AllowUnsafeUpdates = allowSiteUnsefaUpdt;
web.AllowUnsafeUpdates = allowWebUnsafeUpdt;
throw new ApplicationException("ERROR "+ ex.ToString());
}
}
}
}
but it works ok if i have a path like "FOLDER/file.jpg" but it doesn't when i have subfolders "FOLDER/SUB/file.jpg"
can anyone give me some pointers?
My guess is that the problem lies inside your SPCreateFolder method. It should have created folders recursively. As when the you try to add new file with
SPFile newFile = web.Files.Add(filePath, fileData, true); //true = replace
the server relative path must exist. Try following method for folder creation
private static void SPCreateFolder(SPWeb web, string filepath)
{
// since you pass this as Path.GetDictionary it's no longer split by '/'
var foldersTree = filepath.Split('\\');
foldersTree.Aggregate(web.RootFolder, GetOrCreateSPFolder);
}
private static SPFolder GetOrCreateSPFolder(SPFolder sourceFolder, string folderName)
{
SPFolder destination;
try
{
// return the existing SPFolder destination if already exists
destination = sourceFolder.SubFolders[folderName];
}
catch
{
// Create the folder if it can't be found
destination = sourceFolder.SubFolders.Add(folderName);
}
return destination;
}
Then you can execute this with
...
SPCreateFolder(web, Path.GetDirectoryName(filePath));
SPFile newFile = web.Files.Add(filePath, fileData, true); //true = replace
...
Let me know if that helps

Backup Windows 7 with specific filetypes. Some folders unavilable

Im trying to backup a computer with Windows 7 installed.
In older systems I created a backup that found and copyied specific images and office files.
Now when trying in Windows 7, I face some problems regarding some folders that arent available for me like they used to be in older systems.
How can I tweek this problem. I really like this way of backing the system up prior to upgrading etc.
Thanks in advance.
Feel free to ask and comment.
using System;
using System.Collections.Generic;
using System.IO;
//using System.IO.Directory.CreateDirectory;
static class Program
{
static void Main(string[] args)
{
ShowAllFoldersUnder(#"c:\",0);
}
private static void ShowAllFoldersUnder(string path,int indent)
{
int idx = 0;
string sourcePath = #"c:\";
string destinPath = #"h:\20160714\";
string fldr = #"C:\";
string[] fileTypes = new string[2];
fileTypes[idx] = ".docx"; idx++;
fileTypes[idx] = ".xlsx"; idx++;
try
{
if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
{
foreach (string folder in Directory.GetDirectories( path ) )
{
//Console.WriteLine(folder);
//if (#folder.IndexOf(fldr) != -1) // COMMENT
//{
Console.WriteLine( folder );
foreach ( string file in Directory.GetFiles( folder ) )
{
string e = Path.GetExtension( file );
//Console.WriteLine(e);
for (int i =0;i<=fileTypes.GetUpperBound(0);i++)
{
string[] filesToCopy = Directory.GetFiles(folder, "*" + Convert.ToString(fileTypes[i]));
foreach (string name in filesToCopy)
{
if (Convert.ToString(fileTypes[i]).ToLower() == Path.GetExtension(file).ToLower())
{
Console.WriteLine("From: {0}",name);
Console.WriteLine("To: {0}", name.Replace(sourcePath, destinPath) );
try
{
DirectoryInfo di = Directory.CreateDirectory( Path.GetDirectoryName( name.Replace(sourcePath, destinPath) ) );
Console.WriteLine("Copying.");
File.Copy(name, name.Replace(sourcePath, destinPath), true);
}
catch (Exception ex)
{
Console.WriteLine("The process failed: {0}", ex.ToString());
}
finally {}
}
}
}
}
// break;
//}
ShowAllFoldersUnder(folder, indent);
}
}
}
catch (UnauthorizedAccessException)
{ }
}
}

C# Upload whole directory using FTP

What I'm trying to do is to upload a website using FTP in C# (C Sharp). So I need to upload all files and folders within a folder, keeping its structure. I'm using this FTP class: http://www.codeproject.com/Tips/443588/Simple-Csharp-FTP-Class for the actual uploading.
I have come to the conclusion that I need to write a recursive method that goes through every sub-directory of the main directory and upload all files and folders in it. This should make an exact copy of my folder to the FTP. Problem is... I have no clue how to write a method like that. I have written recursive methods before but I'm new to the FTP part.
This is what I have so far:
private void recursiveDirectory(string directoryPath)
{
string[] filePaths = null;
string[] subDirectories = null;
filePaths = Directory.GetFiles(directoryPath, "*.*");
subDirectories = Directory.GetDirectories(directoryPath);
if (filePaths != null && subDirectories != null)
{
foreach (string directory in subDirectories)
{
ftpClient.createDirectory(directory);
}
foreach (string file in filePaths)
{
ftpClient.upload(Path.GetDirectoryName(directoryPath), file);
}
}
}
But its far from done and I don't know how to continue. I'm sure more than me needs to know this! Thanks in advance :)
Ohh and... It would be nice if it reported its progress too :) (I'm using a progress bar)
EDIT:
It might have been unclear... How do I upload a directory including all sub-directories and files with FTP?
Problem Solved! :)
Alright so I managed to write the method myslef. If anyone need it feel free to copy:
private void recursiveDirectory(string dirPath, string uploadPath)
{
string[] files = Directory.GetFiles(dirPath, "*.*");
string[] subDirs = Directory.GetDirectories(dirPath);
foreach (string file in files)
{
ftpClient.upload(uploadPath + "/" + Path.GetFileName(file), file);
}
foreach (string subDir in subDirs)
{
ftpClient.createDirectory(uploadPath + "/" + Path.GetFileName(subDir));
recursiveDirectory(subDir, uploadPath + "/" + Path.GetFileName(subDir));
}
}
It works very well :)
I wrote an FTP classe and also wrapped it in a WinForms user control. You can see my code in the article An FtpClient Class and WinForm Control.
I wrote a reusable class to upload entire directory to an ftp site on windows server, the program also renames the old version of that folder (i use it to upload my windows service program to the server).
maybe some need this:
class MyFtpClient
{
protected string FtpUser { get; set; }
protected string FtpPass { get; set; }
protected string FtpServerUrl { get; set; }
protected string DirPathToUpload { get; set; }
protected string BaseDirectory { get; set; }
public MyFtpClient(string ftpuser, string ftppass, string ftpserverurl, string dirpathtoupload)
{
this.FtpPass = ftppass;
this.FtpUser = ftpuser;
this.FtpServerUrl = ftpserverurl;
this.DirPathToUpload = dirpathtoupload;
var spllitedpath = dirpathtoupload.Split('\\').ToArray();
// last index must be the "base" directory on the server
this.BaseDirectory = spllitedpath[spllitedpath.Length - 1];
}
public void UploadDirectory()
{
// rename the old folder version (if exist)
RenameDir(BaseDirectory);
// create a parent folder on server
CreateDir(BaseDirectory);
// upload the files in the most external directory of the path
UploadAllFolderFiles(DirPathToUpload, BaseDirectory);
// loop trough all files in subdirectories
foreach (string dirPath in Directory.GetDirectories(DirPathToUpload, "*",
SearchOption.AllDirectories))
{
// create the folder
CreateDir(dirPath.Substring(dirPath.IndexOf(BaseDirectory), dirPath.Length - dirPath.IndexOf(BaseDirectory)));
Console.WriteLine(dirPath.Substring(dirPath.IndexOf(BaseDirectory), dirPath.Length - dirPath.IndexOf(BaseDirectory)));
UploadAllFolderFiles(dirPath, dirPath.Substring(dirPath.IndexOf(BaseDirectory), dirPath.Length - dirPath.IndexOf(BaseDirectory))
}
}
private void UploadAllFolderFiles(string localpath, string remotepath)
{
string[] files = Directory.GetFiles(localpath);
// get only the filenames and concat to remote path
foreach (string file in files)
{
// full remote path
var fullremotepath = remotepath + "\\" + Path.GetFileName(file);
// local path
var fulllocalpath = Path.GetFullPath(file);
// upload to server
Upload(fulllocalpath, fullremotepath);
}
}
public bool CreateDir(string dirname)
{
try
{
WebRequest request = WebRequest.Create("ftp://" + FtpServerUrl + "/" + dirname);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Proxy = new WebProxy();
request.Credentials = new NetworkCredential(FtpUser, FtpPass);
using (var resp = (FtpWebResponse)request.GetResponse())
{
if (resp.StatusCode == FtpStatusCode.PathnameCreated)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return false;
}
}
public void Upload(string filepath, string targetpath)
{
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(FtpUser, FtpPass);
client.Proxy = null;
var fixedpath = targetpath.Replace(#"\", "/");
client.UploadFile("ftp://" + FtpServerUrl + "/" + fixedpath, WebRequestMethods.Ftp.UploadFile, filepath);
}
}
public bool RenameDir(string dirname)
{
var path = "ftp://" + FtpServerUrl + "/" + dirname;
string serverUri = path;
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.Rename;
request.Proxy = null;
request.Credentials = new NetworkCredential(FtpUser, FtpPass);
// change the name of the old folder the old folder
request.RenameTo = DateTime.Now.ToString("yyyyMMddHHmmss");
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
using (var resp = (FtpWebResponse)request.GetResponse())
{
if (resp.StatusCode == FtpStatusCode.FileActionOK)
{
return true;
}
else
{
return false;
}
}
}
catch
{
return false;
}
}
}
Create an instance of that class:
static void Main(string[] args)
{
MyFtpClientftp = new MyFtpClient(ftpuser, ftppass, ftpServerUrl, #"C:\Users\xxxxxxxxxxx");
ftp.UploadDirectory();
Console.WriteLine("DONE");
Console.ReadLine();
}
Unless you're doing this for fun or self-improvement, use a commercial module. I can recommend one from Chilkat, but I'm sure there are others.
Note: I'm pretty sure this does answer the stated problem, What I'm trying to do is to upload a website using FTP in C# (C Sharp).

Categories

Resources