How to programatically create a folder at a Sharepoint site - c#

this question is related with this one. How can I create a folder to put the files I upload inside them without using the SharePoint API (I'm executing the application on another host)?
Thanks in advance.

SPSite _MySite = new SPSite("http://adfsaccount:2222/");
SPWeb _MyWeb = _MySite.OpenWeb();
SPDocumentLibrary _MyDocLibrary = (SPDocumentLibrary) _MyWeb.Lists["My Documents"];
SPFolderCollection _MyFolders = _MyWeb.Folders;
_MyFolders.Add("http://adfsaccount:2222/My%20Documents/" + txtUpload.Text + "/");
_MyDocLibrary.Update();
_MyWeb.Dispose();
_MySite .Dispose();

I created console application to create folders. I need to give seperate permissions for each and every folder because those are all state folders. So you can look at the breakroleinheritence property also.

Related

Getting files from Sharepoint using .Net

Good afternoon, I am using the Microsoft.SharePointOnline.CSOM library to work with Sharepoint. I have a code where I get a list called MyDoc like this:
using (var context = new ClientContext(url)
{
varweb = context.Web;
var list = web.Lists.GetByTitle("MyDocs");
}
Then I iterate through all the folders to find a folder with a suitable name and get files from there. With the help of file.ServerRelativeUrl I found out the link to the file on Sharepoint:
/MyDocs/Documents/Students/Homework/1lesson.pdf
How can I immediately access the Homework folder and download all the files from there without going through all the possible folders in the MyDocs sheet?
Instead of getting the list, just use the method GetFolderByServerRelativeUrl within the context.Web object
var folder = context.Web.GetFolderByServerRelativeUrl("/MyList/MyFolder");
context.Load(folder);
context.ExecuteQuery();

Drive API v3, C# - Folder Hierarchy

I've got an app that communicates with Drive (specifically TeamDrives) and I need to pull a hierarchical folder structure within a given TeamDrive.
I can list my available TeamDrives then get the files (filter: folders mime type) within them but there doesn't seem to be any parent info to each folder so my structure is seemingly 'flat'.
I get that on Drive a folder is just a label and that 'sub-folders' could be shared in several places so I will cater for that but I just want to be able to create the directory tree on my app.
e.g. structure as I want to show it in my app:
Team Drive Name
Main Folder
Sub Folder
My 'list' code:
var request = service.Files.List();
request.Corpora = "teamDrive";
request.IncludeTeamDriveItems = true;
request.SupportsTeamDrives = true;
request.OrderBy = "name";
request.PageSize = 100;
request.TeamDriveId = "[teamDriveId]";
request.Q = "mimeType='application/vnd.google-apps.folder'";
This gives me for a given 'teamDriveId':
Main Folder
Sub Folder
parent on the Sub Folder result is null.
You haven't specified which fields you want in the response, so you are getting the default which doesn't include parent information. Try adding request.Fields = "*". I'm not familiar with the library you are using, so I might have the wrong syntax - please double check.
You might also find this useful In Google Apps Script, how would I get all subfolders and all subsubfolders and all subsubsub folders etc.?
As pinoyyid suggested you need to add 'Fields' to your request.
request.Fields = "name, id, parents";
https://developers.google.com/drive/api/v3/folder

FileUpload does not let me to save

I have a confusing problem. I'm trying to use FileUpload. The following code works well locally:
var postedFile = uploader.PostedFile;
var fileName = Path.GetFileName(postedFile.FileName);
var extension = Path.GetExtension(fileName);
var newFile = Guid.NewGuid() + extension;
var imageFilePath = Path.Combine(this.Server.MapPath("~/ProductImages"), newFile);
uploader.SaveAs(imageFilePath);
But when I publish my code to my server in internet the following exception occurs:
Could not find a part of the path [...]
When I change uploader.SaveAs(imageFilePath); to uploader.SaveAs(imageFilePath.Replace(this.Request.ServerVariables["APPL_PHYSICAL_PATH"], "..\\"));, this exception occurs:
The SaveAs method is configured to require a rooted path, and the path [..] is not rooted.
Would any one tell me how to use an Uploader? And how I can solve this problem?
With thanks
There is no problem in your code. When you run an application over the a web server, web server manged by a user in OS.(for examle nobody for enginx or Application Pool group in IIS).
You should set permission for folder that you want save the data. this my be done in your hosting file manager panel or via direct access to OS.
The problem is that local accounts aren't valid on remote resources on active directory - you need to connect as ComputerName$ or Anonymous depending on the type of local identity that you are using.
I was able to upload on debug mode but not on published site, so that might help you Mohammad.
Are you sure the folder ProductImages exists on the server?
You can try to call
Directory.CreateDirectory(this.Server.MapPath("~/ProductImages"))
before saving the file. It will create the directory if it doesn't exists or do nothing if it exists.
I finally solved the problem by setting the permission on the folder. I set the write permission on "Application pool group" for that folder and now I can upload any file there, by my app.
Thanks
Try this one.. for uploading and insert the values in database..
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(Server.MapPath("~/" + filename));
Stream str = FileUpload1.PostedFile.InputStream;
con.Open();
SqlCommand cmds = new SqlCommand("insert into datas(name,path,types,pricing)values(#name,#path,#types,#pricing)", con);
cmds.Parameters.AddWithValue("#name",d);
cmds.Parameters.AddWithValue("#path", filename);
cmds.Parameters.AddWithValue("#types", RadioButton1.Text);
cmds.Parameters.AddWithValue("#pricing", "FineGrained");
cmds.ExecuteNonQuery();
Response.Write("<script>alert('successfully uploaded');</script>");

Use of ServerMapPath in C#

In a block of code, i have the following line:
CsvFile= #"D:\Web\Preps\en\csr\downloadcenter\ClickCounter.csv";
I try to use Server.MapPath instead:
CsvFile = Server.MapPath(#"../en/csr/downloadcenter/ClickCounter.csv");
(the file from where i write this line is located at the same level as "csr" but in a different folder)
I don't have any errors appearing since i'm not using visual studio. Does anyone know what i'm doing wrong ? Thanks for your help
You said that your file is in a folder at the same level of the csr folder, something like
D:\Web\Preps\en\YourFolder, am I right ? Then, your path is not correct.
Try this :
CsvFile = Server.MapPath(#"../csr/downloadcenter/ClickCounter.csv");
or this :
CsvFile = Server.MapPath(#"../../en/csr/downloadcenter/ClickCounter.csv");
The reason your path is not correct is because the way you're using it, you're trying to access
D:\Web\Preps\en\en\csr\downloadcenter\ClickCounter.csv. There is an unneeded en
Assuming that the directory you are after is "under" your web site directory then:
Server.MapPath("~/")
Will take you to the root of your website, from there navigate to somewhere else i.e.
Server.MapPath("~/en/csr/downloadcenter/ClickCounter.csv")
If you don't want to get to the root of your site and it's located somewhere else on the server, then I have misunderstood the question. In this instance you will need to ensure the site has permissions to the respective directory.

ASP.NET MVC Website Read File from Disk Problem

I'm reading a text file containing an insert statement for SQL using C# in an MVC Website I'm working on. When debugging the function I'm using works fine and the insert occurs. But once I publish the site and run it on my local machine (with IIS set-up to use asp.net 4.0 even) it doesn't seem to work.
if (Request.Files != null && Request.Files["txtImportFile"] != null)
{
//newFilePath = Server.MapPath("\\" + DateTime.Now.Ticks + Request.Files["txtImportFile"].FileName);
string[] temp_string = Request.Files["txtImportFile"].FileName.Split(new char[] { '\\' });
string temp_filename = temp_string[temp_string.Count() - 1];
//newFilePath = Server.MapPath("\\temp\\" + DateTime.Now.Ticks + Request.Files["txtImportFile"].FileName);
newFilePath = Server.MapPath("\\temp\\" + DateTime.Now.Ticks + temp_filename);
Request.Files["txtImportFile"].SaveAs(newFilePath);
StreamReader reader = new StreamReader(newFilePath);
string contents = reader.ReadToEnd();
reader.Close();
Models.WingsRemoteDbLibrary dbLib = new Models.WingsRemoteDbLibrary();
string update_message = dbLib.UpdateSlaveItemsTable(contents);
if (System.IO.File.Exists(newFilePath))
System.IO.File.Delete(newFilePath);
RandomPopupView(update_message);
}
I hope my explanation doesn't sound vague. I'll try my best to answer any further questions. Thanks.
Workaround:
Instead of using
Server.MapPath("\\temp\\"...
Create folder under root with name "temp" and use
System.Web.HttpContext.Current.Request.MapPath("~\\temp....
Well, "it doesn't seem to work" is pretty vague - a bit more detail would be nice! But it sounds like a permissions issue. The default profile in IIS has very little access to the disk, especially write access. It isn't really a good idea to write inside your own site anyway (I'd use an unrelated part of the disk, myself), but you will need to configure IIS to run the application in a specific named identity, with access to the disk. Configuring the account itself (not IIS - the account; for example granting "logon as a service") to run as an ASP.NET account is not particularly trivial, unfortunately.
Another thought: is your app a sub-application, i.e. is your app-root /, or is it /MyApp/ ? The reason I ask is your use of MapPath might be better expressed relative to the app-root, i.e. ~/temp/ - but again I stress; writing inside the app is risky. You really want that folder to be non-executing.
There may be an alternative solution to this problem. You can avoid messing with path and file system altogether if you can 'bake' the file into assembly at build time. Here is how you can do this:
In Visual Studio solution explorer right click on a file and go to Properties.
Set Build Action to 'Embedded Resource'.
Later you can read the file using GetManifestResourceStream:
var stream = GetType()
.Assembly
.GetManifestResourceStream("YourNameSpace.Folder.YourFile.txt");
using (var reader = new StreamReader(stream)) {
var fileContent = reader.ReadToEnd();
}
More info here.

Categories