FileDownload Not working ASP MVC - c#

I'm trying to download a file from server but this thing won't work. Been tring doing it for more than 2 weeks. Here is the code:
IN CSHTML PAGE:
<script type="text/x-jsrender" id="docView">
View
</script>
<script>
function docView(id) {
docId = id;
$.ajax({
type: "GET",
url: '#Url.Action("DownloadFile", "Profile")' + "?docid=" + docId,
dataType: "json",
success: function (result) {
},
});
</script>
IN MVC Controller:
[HttpGet]
public ActionResult DownloadFile(Guid? docid)
{
int i = 1;
string key = ConfigurationManager.AppSettings["PhysicalDocumentPath"];
JApplicantDocument value = new JApplicantDocument();
var response = new Response();
var fName = "";
var savefileName = "";
var fileSavePath = "";
var prevPath = "";
var nextPath = "";
try
{
IApplicantDataService applicantDataService = new ApplicantDataService();
response = applicantDataService.GetDocument(docid, value);
var fileName = value.ApplicantId + "_" + value.DocumentName;
fName = fileName;
savefileName = fileName;
fileSavePath = Path.Combine(key, fileName);
prevPath = fileSavePath;
nextPath = fileSavePath;
var tmp = fileName.Split('.');
var tmp1 = tmp[0];
while (System.IO.File.Exists(nextPath)) //to get the latest file
{
tmp = fileName.Split('.');
fileName = tmp1 + i.ToString();
fileName = fileName + "." + tmp[1];
savefileName = fileName;
nextPath = Path.Combine(key, savefileName);
if (System.IO.File.Exists(nextPath))
{
prevPath = nextPath;
}
i++;
tmp = prevPath.Split(new string[] { "Docs\\" }, StringSplitOptions.None);
fName = tmp[1];
response.Message = prevPath;
}
}
catch (Exception e)
{
Utils.Write(e);
}
return File(prevPath, value.Format);
}
I just want on click of View button to download the file as per this(http://www.c-sharpcorner.com/UploadFile/db2972/file-download-sample-in-mvc-day-40/). i cannot use location.href(...) directly in tag due to the fact that i'm using it in script jsrender which is being used in syncfusion grid controls. Hence I wont be able to get the docid at all.

Related

c# - How to call/link a workflow on a web application from a c# program?

I have a C# (WinForms) application that can scan documents via a printer. After scanning, I will be able to enter document details on it and have a button to finalize the documents. The documents details and info will be stored in my database ABC in certain tables.
Now, I have another web application written in Java(IntelliJ) that has some button functionality to upload documents and then start a workflow and route it to another user to approve the document. I won't go into detail on the specifics. This application also connects to the same database ABC.
So now comes the tougher part, I need to link these two applications in a way that when I finalize my document
on the C# application, it has to auto trigger the workflow on the web application side. Rather than manually starting the workflow on the web application, it would just call or trigger the workflow, so I do not need to access the web application at all for the process to start.
private void FinButton_Click(object sender, EventArgs e)
{
int count = 0;
var txtBoxFields = new List<TextBox>
{
textBox1,
textBox2,
textBox3,
textBox4,
textBox5,
textBox6,
textBox7,
textBox8,
textBox9,
textBox10,
textBox11,
textBox12,
textBox13,
textBox14,
textBox15
};
var templateFields = new List<String>
{
"T1",
"T2",
"T3",
"T4",
"T5",
"T6",
"T7",
"T8",
"T9",
"T10",
"T11",
"T12",
"T13",
"T14",
"T15"
};
//long tid = 0;
//Start insert query into templatebatch table in db
var dbConnection2 = DBConnection.Instance();
dbConnection2.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection2.IsConnect())
{
bool test = true;
for (int i = 1; i <= 15; i++)
{
var input = txtBoxFields[i - 1].Text;
var insertQuery = "INSERT INTO templateinfo(TID, THEADER, " + templateFields[i - 1] + ") VALUES(#tid, #theader,#t" + i + ")";
var insertCmd = new MySqlCommand(insertQuery, dbConnection2.Connection);
insertCmd.Parameters.AddWithValue("#tid", tid);
insertCmd.Parameters.AddWithValue("#theader", "N");
if (String.IsNullOrEmpty(input))
{
count = 1;
insertCmd.Parameters.AddWithValue("#t" + i, String.Empty);
break;
}
else
{
if (test)
{
insertCmd.Parameters.AddWithValue("#t" + i, txtBoxFields[i - 1].Text);
insertCmd.ExecuteNonQuery();
test = false;
var selectQuery = "select TINFOID from templateinfo where TID=" + tid + " and THEADER = 'N'";
var selectCmd = new MySqlCommand(selectQuery, dbConnection2.Connection);
var selectReader = selectCmd.ExecuteReader();
using (MySqlDataReader dr = selectReader)
{
while (dr.Read())
{
tinfoid = Convert.ToInt32(dr["TINFOID"]);
}
}
}
else
{
var updateQuery = "update templateinfo set " + templateFields[i - 1] + "='" + txtBoxFields[i - 1].Text + "' where TINFOID = '" + tinfoid + "' and TID=" + tid + " and THEADER='N'";
var updateCmd = new MySqlCommand(updateQuery, dbConnection2.Connection);
var updateReader = updateCmd.ExecuteReader();
using (var reader = updateReader)
{
}
}
}
}
}
if (count == 1)
{
//MessageBox.Show("Input field(s) cannot be left empty.");
}
//Finalize here
var client = new LTATImagingServiceClient();
client.Finalize(userID, tid, tinfoid, batchID);
Debug.WriteLine(userID + ", " + tid + ", " + tinfoid + ", " + batchID);
var batchName = templateView.SelectedNode.Text;
var folderPath = #"C:\temp\batches\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
ThumbnailLists.Items.Clear();
// var img = Image.FromFile(#"C:\temp\batch-done.png");
if (ImageBox.Image != null)
{
ImageBox.Image.Dispose();
}
ImageBox.Image = null;
try
{
using (new Impersonation(_remoteDomain, _remoteUser, _remotePassword))
{
// MessageBox.Show(_remoteUser);
// MessageBox.Show(_remotePassword);
var tPath = #"\\126.32.3.178\PantonSys\SAM\Storage\3\" + mastertemplatename + #"\" + subtemplatename + #"\" + batchName + #"\";
bool exists = System.IO.Directory.Exists(tPath);
if (!exists)
{
System.IO.Directory.CreateDirectory(tPath);
}
string[] fileList = Directory.GetFiles(folderPath, "*");
foreach (var file in fileList)
{
File.Copy(file, tPath + Path.GetFileName(file));
}
CurrentPageBox.Text = "";
NumberPageBox.Text = "";
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
var dbConnection = DBConnection.Instance();
dbConnection.DatabaseName = ConfigurationManager.AppSettings["dbName"];
if (dbConnection.IsConnect())
{
var deleteBatchQuery = "DELETE FROM templatebatch WHERE batchname ='" + templateView.SelectedNode.Text + "'";
var deleteBatchCmd = new MySqlCommand(deleteBatchQuery, dbConnection.Connection);
var deleteBatchReader = deleteBatchCmd.ExecuteReader();
using (var reader = deleteBatchReader)
{
while (reader.Read())
{
}
}
templateView.Nodes.Remove(templateView.SelectedNode);
Directory.Delete(folderPath, true);
MessageBox.Show("Successfully Transferred.");
foreach (var txtFields in txtBoxFields)
{
txtFields.Text = "";
txtFields.Enabled = false;
}
finButton.Visible = false;
finButton.Enabled = false;
}
bindButton.Visible = false;
}
Would this be possible to achieve or just being far-fetched?
I would appreciate any suggestions or pointers on this. Do let me know if there is anything unclear in my explanation.
EDIT:
Request URL: http://126.32.3.178:8111/process/taskmanager/start/start.jsp
Request Method: POST
Status Code: 200 OK
Remote Address: 126.32.3.178:8111
Referrer Policy: no-referrer-when-downgrade
Is there a way I could call this from the C# application?
You can send your file directly from your C# app with use of Http client. Here is code sample:
private async Task<bool> Upload(string filePath)
{
const string actionUrl = #"http://126.32.3.178:8111/process/taskmanager/start/start.jsp";
var fileName = Path.GetFileName(filePath);
var fileBytes = File.ReadAllBytes(filePath);
var fileContent = new ByteArrayContent(fileBytes);
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileContent, fileName);
var response = await client.PostAsync(actionUrl, formData);
return response.IsSuccessStatusCode;
}
}
Also, note that there maybe some sort of authentication should be performed before you can post a request.

how not to overwrite in FileUpload in C#

in the code below
public class UploadController : ApiController
{
[HttpPost]
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/Files/" + postedFile.FileName);
postedFile.SaveAs(filePath);
var fileName = postedFile.FileName;
var extension = Path.GetExtension(fileName);
var nameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
var i = 1;
while (File.Exists(filePath + fileName))
{
fileName = nameWithoutExtension.Trim() + " (" + i + ")" + extension;
i++;
}
docfiles.Add(filePath + fileName);
// docfiles.Add(filePath);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
}
I really want to make a file upload the classic filename(1).jpg if file name is already exists but the code I had still delete the old files that has the same name, I don't know where I got it wrong i used while loop but it wasnt working
I tried fixing it the code below is working now it turns out i constructed it wrong :)
var filePath = HttpContext.Current.Server.MapPath("~/Files/" );
var postedFile = httpRequest.Files[file];
var fileName = postedFile.FileName;
var extension = Path.GetExtension(fileName);
var nameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
var i = 1;
while (File.Exists(filePath + fileName))
{
fileName = nameWithoutExtension.Trim() + " (" + i + ")" + extension;
i++;
}
postedFile.SaveAs(filePath + fileName);

Upload File on Multiple File Upload Control Simultaneously Using jQuery and ASP.Net Handler

I have a form with multiple file upload control and a handler to upload file in chunk. This is working fine for upload a single file on an upload control at a time. But I want to upload file on multiple upload control simultaneously with chunk upload.Please suggest.
$(inputUploadElem).fileupload({
url: '../Handler.ashx?upload=start',
maxChunkSize: 10000000,
// fileInput: $(this).prop("files"),
sequentialUploads: true,
dropZone: $(this),
//singleFileUploads: false,
// limitMultiFileUploads: 1,
add: function (e, data) {
var uploadErrors = [];
globalid = $(this).attr("id");
var file = data.files[0];
oldfname = file.name;
var name = file.name;
var fname = name.substring(0, name.lastIndexOf("."));
var ext = name.substring(name.lastIndexOf("."));
var dt = new Date();
var month = dt.getMonth() + 1;
var day = dt.getDate();
var strTempImg = "_" + dt.getFullYear() + "_" + (month < 10 ? '0' : '') + month + "_" + (day < 10 ? '0' : '') + day + "-" + dt.getHours() + dt.getMinutes() + dt.getSeconds();
filename = fname + strTempImg + ext;
globalid = $(this).attr('id');
pathToUpload = $(this).attr('path');
PathByControl = '';
if (uploadErrors.length > 0) {
alert(uploadErrors.join("\n"));
}
else
data.submit();
},
formData: function (data) {
var arrFormData = [];
arrFormData.push({ name: "file", value: filename });
arrFormData.push({ name: "controlid", value: globalid });
arrFormData.push({ name: "RootPath", value: pathToUpload });
arrFormData.push({ name: "PathByControl", value: PathByControl });
return arrFormData;
},
done: function (response, status) {
PopulateData(globalid);
$('.uploadprogress', "#UploadDiv_" + globalid.substring(globalid.indexOf('_') + 1, globalid.length)).css('visibility', 'hidden');
},
success: function (response, status) {
if (!(response === undefined || response == null))
{
var repData = JSON.parse(response);
//Sending conditional path for next chunk
PathByControl = respData.PathByControl;
}
},
error: function (error) {
$('.uploadprogress', "#UploadDiv_" + globalid.substring(globalid.indexOf('_') + 1, globalid.length)).css('visibility', 'hidden');
alert("An error has occurred during processing your request.");
},
chunksend: function (e, data) {
},
progress: function (e, data) {
// Track Progress
var progress = parseInt(data.loaded / data.total * 100, 10);
$('.uploadprogress', "#UploadDiv_" + globalid.substring(globalid.indexOf('_') + 1, globalid.length)).css('display', '');
$('.uploadprogress', "#UploadDiv_" + globalid.substring(globalid.indexOf('_') + 1, globalid.length)).css('visibility', 'visible');
$('.uploadprogress', "#UploadDiv_" + globalid.substring(globalid.indexOf('_') + 1, globalid.length)).css('width', progress + '%');
}
});
<%# WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Configuration;
using System.Net;
using System.IO;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
System.Collections.Specialized.NameValueCollection headers = context.Request.Headers;
string rootPath = string.Empty,nodifiedFileName=String.Empty,controlId=String.Empty,pathByControl=String.Empty;
if (context.Request.Form.Count >0 )
{
nodifiedFileName = context.Request.Form["file"];
controlId = context.Request.Form["controlid"];
rootPath = context.Request.Form["RootPath"];
pathByControl = context.Request.Form["PathByControl"];
}
HttpRequest Request = context.Request;
long chunks = 0;
long chunk = 0;
var Range = headers["Content-Range"];
string startPosition = String.Empty;
if (Range != null)
{
string[] arr = Range.ToString().Split('/');
chunks = Convert.ToInt64(arr[1]) - 1;
chunk = Convert.ToInt64(arr[0].Split('-')[1]);
startPosition = arr[0].Split('-')[0].Trim();
}
HttpFileCollection SelectedFiles = context.Request.Files;
try
{
HttpFileCollection files = Request.Files;
HttpPostedFile postedFile = files[0];
string filename = postedFile.FileName;
HttpPostedFile PostedFile = SelectedFiles[0];
string strFileName = Request.Form[0];
Stream sreader = postedFile.InputStream;
long length = postedFile.InputStream.Length;
byte[] bytes = new byte[length];
int bytetoread = sreader.Read(bytes, 0, bytes.Length);
byte[] buffer = bytes;
if (startPosition.Equals("bytes 0") || String.IsNullOrEmpty(startPosition))
{
// If first chunk the get conditional path from DB by control id
pathByControl = GetPathFromDBByControlId(controlId);
}
if (chunk != chunks)
{
//Returning conditionl path for remain chunk
context.Response.Write("{\"PathByControl\":\"" + pathByControl + "\"}");
}
// Uploading file on FTP server
UploadFileOnFTP(strFileName, rootPath + pathByControl + nodifiedFileName, buffer, chunk, chunks);
if (chunk == chunks)
{
//If all chunks are uploaded then insert detail in DB
InsertFileDetailInDB(rootPath + pathByControl + nodifiedFileName, nodifiedFileName, PostedFile.FileName);
}
}
catch (Exception ex)
{
context.Response.Clear();
context.Response.Write("{\"Error\":\"" + ex.Message+"\"}");
GC.Collect();
}
}
public bool IsReusable
{
get
{
return false;
}
}
public string GetPathFromDBByControlId(String ControlId)
{
return "";
}
public void UploadFileOnFTP(string _FileName, string _UploadPath, byte[] bufferToWrite, long chunk, long chunks)
{
string ftphost = ConfigurationManager.AppSettings["FTP_IP"].ToString();
string ftpfullpath = "ftp://" + ftphost + "/" + _UploadPath;
string _FTPUser = Convert.ToString(ConfigurationManager.AppSettings["FTP_USER"]);
string _FTPPass = Convert.ToString(ConfigurationManager.AppSettings["FTP_PASS"]);
try
{
System.Net.FtpWebRequest _FtpWebRequest = (System.Net.FtpWebRequest)System.Net.FtpWebRequest.Create(new Uri(ftpfullpath));
// Provide the WebPermission Credintials
_FtpWebRequest.Credentials = new System.Net.NetworkCredential(_FTPUser, _FTPPass);
// By default KeepAlive is true, where the control connection is not closed
// after a command is executed.
_FtpWebRequest.KeepAlive = true;
// set timeout for 20 seconds
_FtpWebRequest.Timeout = -1;
// Specify the command to be executed.
_FtpWebRequest.Method = System.Net.WebRequestMethods.Ftp.AppendFile;
// Specify the data transfer type.
_FtpWebRequest.UseBinary = true;
using (Stream _Stream = _FtpWebRequest.GetRequestStream())
{
// System.IO.Stream _Stream = _FtpWebRequest.GetRequestStream();
_Stream.Write(bufferToWrite, 0, bufferToWrite.Length);
// Close the file stream and the Request Stream
_Stream.Close();
_Stream.Dispose();
GC.Collect();
}
}
catch (Exception ex)
{
throw ex;
}
}
public void InsertFileDetailInDB(String Path, String ModifiedName, String OrigionalName)
{
}
}

Refresh in browser when uploading mvc file c #

I have an AJAX file upload by call to MVC C# driver, but the browser refreshes and reloads the page.
But if I comment the line that saves the file in the driver does not happen that is only when the file is saved on the server. File.SaveAs (fname);
MVC controller:
[HttpPost]
public ActionResult UploadDocument()
{
if (Request.Files.Count > 0)
{
try
{
FileUpdateDto fileModal = new FileUpdateDto();
HttpFileCollectionBase files = Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
string fname;
DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/Content/Document/" + UserId).ToString());
if (!directory.Exists)
{
Directory.CreateDirectory(Server.MapPath("~/Content/Document/" + UserId).ToString());
}
if (Request.Browser.Browser.ToUpper() == "IE" || Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
var guidnew = Guid.NewGuid();
fname = Path.Combine(Server.MapPath("~/Content/Document/" + UserId), guidnew + "." + fname.Split('.')[1].ToString());
fileModal.FileName = fname;
fileModal.Path = directory.ToString();
fileModal.DateFileUpload = DateTime.Now;
file.SaveAs(fname); // If I comment this line without refreshing the browser but does not save the file
}
return Json(fileModal);
}
catch (Exception ex)
{
return Json("Error occurred. Error details: " + ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
Call Ajax in JavaScript:
UploadDocument: function () {
if (window.FormData !== undefined) {
var fileUpload = $("#AdviserFileUpload").get(0);
var files = fileUpload.files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
//fileData.append('username', 'Manas');
$.ajax({
url: site.baseUrl + '/Api/Upload/Document',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function (result) {
__this._AdviserDocumentFile = result;
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("FormData is not supported.");
}
}
I believe I found the solution. The cause is that Visual Studio's "Enable Reload on Save" property is True.
Go to Tools - Options - Web - Browser Reload on Save - Enable Reload on Save and make it false.
Im working with VS2015 and this worked for me, hope it works for you too.
Source

Creating Folders dynamically using CSOM in sharepoint causes ID issues for the document

I am creating the nested folders dynamically for a document library and uploading files. The below code is working fine. but the issues is whenever i uploading the file to the existence folder the ID of the document for the uploaded documents is not in sequence. Suppose if i am uploading a file to path projects\PRJ1\Assignment, fist time it was creating the folders and file with ID's(1\2\3\4) respectively . If i upload other document to the same folder the id of the folders is not changing but the id of the file is 8. i am not unable to find the id 5,6,7 in the document library.
using (CSOM.ClientContext clientContext = new CSOM.ClientContext(SPserverUrl))
{
clientContext.Credentials = new System.Net.NetworkCredential(Username, Password, Domain);
CSOM.Web _Site = clientContext.Web;
// string listrootfolder = "Testlist";
CSOM.List _List = _Site.Lists.GetByTitle("Testlist");
clientContext.Load(_List.RootFolder);
clientContext.ExecuteQuery();
string listrootfolder = _List.RootFolder.Name.ToString();
var folder = CreateFolder(clientContext.Web, "Testlist", folderpath);
// uploading the document
CSOM.FileCreationInformation newFile = new CSOM.FileCreationInformation();
// newFile.Content = System.IO.File.ReadAllBytes(#"D:\Testupload.docx");
byte[] bytes = Convert.FromBase64String(objReqDocumentDetials.FileData.ToString());
newFile.Content = bytes;
// newFile.Url = objDocumentDetials.AttachmentName.ToString() + DateTime.Now.ToString("ddMMyyyyHHmmsss") + "." + objDocumentDetials.FileType.ToString();
newFile.Url = objReqDocumentDetials.FileName.ToString() + "." + objReqDocumentDetials.FileType.ToString();
newFile.Overwrite = true;
Microsoft.SharePoint.Client.File _UploadingFile = folder.Files.Add(newFile);
var item = _UploadingFile.ListItemAllFields;
// var folder = item.GetFolder("account/" + folderName);
// item["Year"] = DateTime.Now.Year.ToString();
// item.Update();
clientContext.Load(_UploadingFile, f => f.ListItemAllFields);
clientContext.ExecuteQuery();
}
public CSOM.Folder CreateFolder(CSOM.Web web, string listTitle, string fullFolderPath)
{
if (string.IsNullOrEmpty(fullFolderPath))
throw new ArgumentNullException("fullFolderPath");
CSOM.List list = web.Lists.GetByTitle(listTitle);
return CreateFolderInternal(web, list.RootFolder, fullFolderPath);
}
public CSOM.Folder CreateFolderInternal(CSOM.Web web, CSOM.Folder parentFolder, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string folderUrl = folderUrls[0];
var curFolder = parentFolder.Folders.Add(folderUrl);
web.Context.Load(curFolder);
web.Context.ExecuteQuery();
if (folderUrls.Length > 1)
{
var folderPath = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
return CreateFolderInternal(web, curFolder, folderPath);
}
return curFolder;
}
The issue was fixed after redefined the CreateFolder and CreateFolderInternal methods as below
public CSOM.Folder CreateFolder(CSOM.Web web, string listTitle, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
CSOM.List _List = web.Lists.GetByTitle(listTitle);
web.Context.Load(_List.RootFolder);
web.Context.ExecuteQuery();
string listrootfolder = _List.RootFolder.Name.ToString();
web.Context.Load(web, w => w.ServerRelativeUrl);
web.Context.ExecuteQuery();
string root = "";
for (int i = 0; i < folderUrls.Length; i++)
{
root = folderUrls[i].ToString();
string targetFolderUrl = "/" + listrootfolder + "/" + string.Join("/", folderUrls, 0, i + 1);
var folder1 = web.GetFolderByServerRelativeUrl(targetFolderUrl);
web.Context.Load(folder1);
bool exists = false;
try
{
web.Context.ExecuteQuery();
exists = true;
}
catch (Exception ex)
{
}
if (!exists)
{
if (i == 0)
{
CreateFolderInternal(web, _List.RootFolder, root);
}
else
{
web.Context.Load(web, w => w.ServerRelativeUrl);
web.Context.ExecuteQuery();
var targetfolderUrls = targetFolderUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string jj = string.Join("/", targetfolderUrls, 0, targetfolderUrls.Length - 1);
CSOM.Folder folder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + jj);
web.Context.Load(folder);
web.Context.ExecuteQuery();
SPCreateFolderInternal(web, folder, root);
}
}
else
{
//already folder exists
}
}
CSOM.Folder finalfolder = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + listrootfolder + "/" + fullFolderPath);
web.Context.Load(finalfolder);
web.Context.ExecuteQuery();
return finalfolder;
}
private void CreateFolderInternal(CSOM.Web web, CSOM.Folder parentFolder, string fullFolderPath)
{
try
{
var curFolder = parentFolder.Folders.Add(fullFolderPath);
web.Context.Load(curFolder);
web.Context.ExecuteQuery();
}
catch (System.Exception ex)
{
}
}

Categories