I need to copy a particular file from one library to another library.
At first, need to check if file is existing in that library.
If Existing, then need to overwrite file content and new sharepoint version should be updated for that document.
I need to do this using c# CSOM and sharepoint version is 2013.
Thanks in advance :)
public static void CopyDocuments(string srcUrl, string destUrl, string srcLibrary, string destLibrary, Login _login)
{
// set up the src client
SP.ClientContext srcContext = new SP.ClientContext(srcUrl);
srcContext.AuthenticationMode = SP.ClientAuthenticationMode.FormsAuthentication;
srcContext.FormsAuthenticationLoginInfo = new SP.FormsAuthenticationLoginInfo(_login.UserName, _login.Password);
// set up the destination context (in your case there is no needs to create a new context, because it would be the same library!!!!)
SP.ClientContext destContext = new SP.ClientContext(destUrl);
destContext.AuthenticationMode = SP.ClientAuthenticationMode.FormsAuthentication;
destContext.FormsAuthenticationLoginInfo = new SP.FormsAuthenticationLoginInfo(_login.UserName, _login.Password);
// get the list and items
SP.Web srcWeb = srcContext.Web;
SP.List srcList = srcWeb.Lists.GetByTitle(srcLibrary);
SP.ListItemCollection col = srcList.GetItems(new SP.CamlQuery());
srcContext.Load(col);
srcContext.ExecuteQuery();
// get the new list
SP.Web destWeb = destContext.Web;
destContext.Load(destWeb);
destContext.ExecuteQuery();
foreach (var doc in col)
{
try
{
if (doc.FileSystemObjectType == SP.FileSystemObjectType.File)
{
// get the file
SP.File f = doc.File;
srcContext.Load(f);
srcContext.ExecuteQuery();
// build new location url
string nLocation = destWeb.ServerRelativeUrl.TrimEnd('/') + "/" + destLibrary.Replace(" ", "") + "/" + f.Name;
// read the file, copy the content to new file at new location
SP.FileInformation fileInfo = SP.File.OpenBinaryDirect(srcContext, f.ServerRelativeUrl);
SP.File.SaveBinaryDirect(destContext, nLocation, fileInfo.Stream, true);
}
if (doc.FileSystemObjectType == SP.FileSystemObjectType.Folder)
{
// load the folder
srcContext.Load(doc);
srcContext.ExecuteQuery();
// get the folder data, get the file collection in the folder
SP.Folder folder = srcWeb.GetFolderByServerRelativeUrl(doc.FieldValues["FileRef"].ToString());
SP.FileCollection fileCol = folder.Files;
// load everyting so we can access it
srcContext.Load(folder);
srcContext.Load(fileCol);
srcContext.ExecuteQuery();
foreach (SP.File f in fileCol)
{
// load the file
srcContext.Load(f);
srcContext.ExecuteQuery();
string[] parts = null;
string id = null;
if (srcLibrary == "My Files")
{
// these are doc sets
parts = f.ServerRelativeUrl.Split('/');
id = parts[parts.Length - 2];
}
else
{
id = folder.Name;
}
// build new location url
string nLocation = destWeb.ServerRelativeUrl.TrimEnd('/') + "/" + destLibrary.Replace(" ", "") + "/" + id + "/" + f.Name;
// read the file, copy the content to new file at new location
SP.FileInformation fileInfo = SP.File.OpenBinaryDirect(srcContext, f.ServerRelativeUrl);
SP.File.SaveBinaryDirect(destContext, nLocation, fileInfo.Stream, true);
}
}
}
catch (Exception ex)
{
Log("File Error = " + ex.ToString());
}
}
}
Source: https://sharepoint.stackexchange.com/questions/114033/how-do-i-move-files-from-one-document-library-to-another-using-jsom
I strongly advise against using the approach suggested by Nikerym. You don't want to download the bytes only to upload them unmodified. It's slow and error-prone. Instead, use the built-in method provided by the CSOM API.
https://learn.microsoft.com/en-us/previous-versions/office/sharepoint-server/mt162553(v=office.15)?redirectedfrom=MSDN
var srcPath = "https://YOUR.sharepoint.com/sites/xxx/SitePages/Page.aspx";
var destPath = $"https://YOUR.sharepoint.com/sites/xxx/SitePages/CopiedPage.aspx";
MoveCopyUtil.CopyFileByPath(ctx, ResourcePath.FromDecodedUrl(srcPath), ResourcePath.FromDecodedUrl(destPath), false, new MoveCopyOptions());
ctx.ExecuteQuery();
You can configure the override behavior by adjusting the 4th and 5th arguments of the function signature.
[...]
bool overwrite,
MoveCopyOptions options
https://learn.microsoft.com/en-us/previous-versions/office/sharepoint-server/mt844930(v=office.15)
Related
I need to download text file from FileCabinet in NetSuite. I am able to search for all files in a folder and get back the file size, name and URL. But when I check the 'content' property, it is NULL. How can I download the file locally?
I tried using the URL to download the file using WebClient, but it returns 403 which makes sense.
var result = Client.Service.search(fileSearch);
var recordList = (Record[])result.recordList;
if (recordList != null && recordList.Length != 0)
{
foreach (var item in recordList)
{
var file = (com.netsuite.webservices.File)item;
int fileSize = (int)file.fileSize; // Returns the correct file size
byte[] fileContent = file.content; // NULL reference ??
Console.WriteLine(file.url + " ==== " + file.name );
// How to download the File from the url above??
// Can't do this, 403 error, below client dont use the same security context
//using (var client = new WebClient())
//{
// client.UseDefaultCredentials = false;
// client.DownloadFile(baseUrl + file.url, file.name);
//}
}
}
I expected 'content' to contain the file content.
When you execute a search, the search results do not include the contents of the file, but you DO have the file id. Below is an extension method on the NetSuite service to get a file by it's id:
public static NetSuite.File GetFileById(this NetSuiteService ns, int fileId)
{
var file = new NetSuite.File();
var response = ns.get(new RecordRef()
{
type = RecordType.file,
internalId = fileId.ToString(),
typeSpecified = true
});
if (response.status.isSuccess)
{
file = response.record as File;
}
return file;
}
var f = ns.GetFileById(3946);
var path = Path.Combine(Directory.GetCurrentDirectory(), f.name);
var contents = f.content;
System.IO.File.WriteAllBytes(path, contents);
Console.WriteLine($"Downloaded {f.name}");
Guys am trying to read a csv file from the view, get its data , format it and write back into an empty csv file. presently have been able to achieve the first approach, where the challenge is right now is writing back into an empty csv file created , but it happens that the csv file is always blank after writing in the file. can someone help me out if am missing anything. Note " am just reading and writing the field , have got nothing to do with the hearder because the csv file has no header" Am using csvhelper library.
if (file.ContentLength > 0)
{
string origin = "FORMATERCSV";
string destination = "FORMATERCSVDESTINATION";
string curretnDate = Convert.ToString(DateTime.Now.ToShortDateString().Replace(#"/", "_"));
var fileName = Path.GetFileName(file.FileName);
var pathfound = Server.MapPath( #"/" + "Content" + "/" + origin + "/" + curretnDate + "/");
var pathfoundDestination = Server.MapPath(#"/" + "Content" + "/" + destination + "/" + curretnDate + "/");
if (!Directory.Exists(pathfound)) Directory.CreateDirectory(pathfound);
if (!Directory.Exists(pathfoundDestination)) Directory.CreateDirectory(pathfoundDestination);
string PathToStore = string.Format(#"{0}\{1}", pathfound, fileName);
string PathToStoreDestination = string.Format(#"{0}\{1}", pathfoundDestination, fileName);
var path = Path.Combine(pathfound,fileName);
file.SaveAs(PathToStore);
file.SaveAs(PathToStoreDestination);
System.IO.File.WriteAllText(PathToStoreDestination,string.Empty);
StreamReader sr = new StreamReader(PathToStore);
CsvReader csvread = new CsvReader(sr);
csvread.Read();
var shedule = new Shedule()
{
RSA_PIN = csvread.GetField<string>(0),
EMPLOYEE_NAME = csvread.GetField<string>(1),
EMPLOYER_CONTRIBUTION = csvread.GetField<double>(2),
EMPLOYER_VC = csvread.GetField<double>(3),
EMPLOYEE_CONTRIBUTION = csvread.GetField<double>(4),
EMPLOYEE_VC = csvread.GetField<double>(5),
TOTAL_CONTRIBUTION = csvread.GetField<double>(6),
FROM_MONTH = csvread.GetField<string>(7),
FROM_YEAR = csvread.GetField<string>(8),
TO_MONTH = csvread.GetField<string>(9),
TO_YEAR = csvread.GetField<string>(10),
EMPLOYER_CODE = csvread.GetField<string>(11),
EMPLOYER_NAME = csvread.GetField<string>(12),
PTID = csvread.GetField<string>(13),
RECEIVED_DATE = csvread.GetField<string>(14),
};
StreamWriter sw = new StreamWriter(PathToStoreDestination);
CsvWriter scvwrite = new CsvWriter(sw);
scvwrite.WriteField(shedule.RSA_PIN);
scvwrite.WriteField(shedule.EMPLOYER_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYER_VC);
scvwrite.WriteField(shedule.EMPLOYEE_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYEE_VC);
scvwrite.WriteField(shedule.TOTAL_CONTRIBUTION);
scvwrite.WriteField(shedule.FROM_MONTH);
scvwrite.WriteField(shedule.FROM_YEAR);
scvwrite.WriteField(shedule.TO_MONTH);
scvwrite.WriteField(shedule.TO_YEAR);
scvwrite.WriteField(shedule.EMPLOYER_CODE);
scvwrite.WriteField(shedule.EMPLOYEE_NAME);
scvwrite.WriteField(shedule.PTID);
scvwrite.WriteField(shedule.RECEIVED_DATE);
scvwrite.NextRecord();
scvwrite.Flush();
// Gets field by position returning int
// var field = csv.GetField<int>(0);
}
return RedirectToAction("Index");
}
Several things could actually occure.
1) are you sure the file from the view is not empty?
2) If you use a break point when you instantiate your class Schedule. Do you get the data from the CSV.
3) Do you really need to do this 2 step, wouldn't it be better to directly write the content of the original file to the new file?
4) Last but not least don't forget to close your streamwriter or do like so :
using(var sw = new StreamWriter(PathToStoreDestination)){
CsvWriter scvwrite = new CsvWriter(sw);
scvwrite.WriteField(shedule.RSA_PIN);
scvwrite.WriteField(shedule.EMPLOYER_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYER_VC);
scvwrite.WriteField(shedule.EMPLOYEE_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYEE_VC);
scvwrite.WriteField(shedule.TOTAL_CONTRIBUTION);
scvwrite.WriteField(shedule.FROM_MONTH);
scvwrite.WriteField(shedule.FROM_YEAR);
scvwrite.WriteField(shedule.TO_MONTH);
scvwrite.WriteField(shedule.TO_YEAR);
scvwrite.WriteField(shedule.EMPLOYER_CODE);
scvwrite.WriteField(shedule.EMPLOYEE_NAME);
scvwrite.WriteField(shedule.PTID);
scvwrite.WriteField(shedule.RECEIVED_DATE);
scvwrite.Flush();
}
Doing so you don't even need to specify to flush.
using (var sw = new StreamWriter(PathToStoreDestination))
{
sw.AutoFlush = true;
CsvWriter scvwrite = new CsvWriter(sw);
scvwrite.WriteField(shedule.RSA_PIN);
scvwrite.WriteField(shedule.EMPLOYEE_NAME);
scvwrite.WriteField(shedule.EMPLOYER_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYER_VC);
scvwrite.WriteField(shedule.EMPLOYEE_CONTRIBUTION);
scvwrite.WriteField(shedule.EMPLOYEE_VC);
scvwrite.WriteField(shedule.TOTAL_CONTRIBUTION);
scvwrite.WriteField(shedule.FROM_MONTH);
scvwrite.WriteField(shedule.FROM_YEAR);
scvwrite.WriteField(shedule.TO_MONTH);
scvwrite.WriteField(shedule.TO_YEAR);
scvwrite.WriteField(shedule.EMPLOYER_CODE);
scvwrite.WriteField(shedule.EMPLOYER_NAME);
scvwrite.WriteField(shedule.PTID);
scvwrite.WriteField(shedule.RECEIVED_DATE);
scvwrite.NextRecord();
//scvwrite.Flush();
}
i am using dropzone to upload multiple files to the server. files will be uploaded to server while file names will be stored in table.
i am trying to add file names in session.
the problem here is that it doesn't add multiple file names inside single session
here is my code :
string imageSessList = context.Session["imageNames"].ToString(); //if i put this line at the begining, then the debugger doesn't even moves to foreach block
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
string fileName = file.FileName;
string fileExtension = file.ContentType;
string strUploadFileExtension = fileName.Substring(fileName.LastIndexOf(".") + 1);
string strAllowedFileTypes = "***jpg***jpeg***png***gif***bmp***"; //allowed file types
string destFileName = "";
List<string> lstImageNames = new List<string>();
// else upload file
if (!string.IsNullOrEmpty(fileName))
{
if (strAllowedFileTypes.IndexOf("***" + strUploadFileExtension + "***") != -1) //check extension
{
if (context.Request.Files[0].ContentLength < 5 * 1024 * 1024) //check filesize
{
// generate file name
destFileName = Guid.NewGuid().ToString() + "." + strUploadFileExtension;
string destFilePath = HttpContext.Current.Server.MapPath("/resourceContent/") + destFileName;
//Save image names to session
lstImageNames.Add(destFileName);
context.Session["imageNames"] = lstImageNames;
file.SaveAs(destFilePath);
strMessage = "Success " + destFileName;
}
else
{
strMessage = "File Size can't be more than 5 MB.";
}
}
else
{
strMessage = "File type not supported!";
}
}
} // foreach
context.Response.Write(strMessage);
}
here i am able to add only single filename to session, not multiple.
how to store and maintain multiple file names in single session :
context.Session["imageNames"]
you need to get current list from session
List<string> lstImageNames= (List<string>)Session["imageNames"];
if(lstImageNames==null)
lstImageNames = new List<string>(); // create new list in the first time
now add new item to it.
lstImageNames.Add(destFileName);
set back to session
context.Session["imageNames"] = lstImageNames;
I am trying to upload multiple file to a Document Library and also update its coloumn values.
List(Doc Lib) already exists but I am stuck with uploadinf the file
I've tried these methods
using lists.asmx
NetworkCredential credentials = new NetworkCredential("user", "Pass", "domain");
#region ListWebService
ListService.Lists listService = new ListService.Lists();
listService.Credentials = credentials;
List list = cc.Web.Lists.GetByTitle(library);
listService.Url = cc.Url + "/_vti_bin/lists.asmx";
try
{
FileStream fStream = System.IO.File.OpenRead(filePath);
string fName = fStream.Name.Substring(3);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
string attach = listService.AddAttachment(library, itemId.ToString(), Path.GetFileName(filePath), contents);
}
#endregion
catch (System.Web.Services.Protocols.SoapException ex)
{
CSVWriter("Message:\n" + ex.Message + "\nDetail:\n" +
ex.Detail.InnerText + "\nStackTrace:\n" + ex.StackTrace, LogReport);
}
It gives a error ServerException :To add an item to a document library, use SPFileCollection.Add() on AddAttachment()
Using
List lib = cc.Web.Lists.GetByTitle("TestLib");
FileCreationInformation fileInfo = new FileCreationInformation();
fileInfo.Content = System.IO.File.ReadAllBytes("C:\\Users\\AJohn\\Desktop\\sample.docx");
fileInfo.Url = "https://serverm/sites/Testing1/TestLib/sample.docx";
fileInfo.Overwrite = true;
Microsoft.SharePoint.Client.File upFile = lib.RootFolder.Files.Add(fileInfo);
cc.Load(upFile);
cc.ExecuteQuery();
I was able to upload once using this method, but now I am getting ServerException :To add an item to a document library, use SPFileCollection.Add() on cc.ExecuteQuery()
But if at all this method works, what I want is that I should update the coloumn values related to this file. In first method I get item.ID so from there I can update the Coloumn Values
Regarding the second method, the following example demonstrates how to upload a file into Documents library and set it's properties (e.g. Category text field)
using (var ctx = new ClientContext(webUri))
{
var targetList = ctx.Web.Lists.GetByTitle("Documents");
var fileInfo = new FileCreationInformation
{
Url = System.IO.Path.GetFileName(sourcePath),
Content = System.IO.File.ReadAllBytes(sourcePath),
Overwrite = true
};
var file = targetList.RootFolder.Files.Add(fileInfo);
var item = file.ListItemAllFields;
item["Category"] = "User Guide";
item.Update();
ctx.ExecuteQuery();
}
I'm using Microsoft Expression Encoder and this is my code
using (LiveJob job = new LiveJob())
{
// Creates file source for encoding
LiveFileSource fileSource = job.AddFileSource(DataDirectory);
// Sets playback to loop on reaching the end of the file
fileSource.PlaybackMode = FileSourcePlaybackMode.Jump;
// Sets this source as the current active one
job.ActivateSource(fileSource);
job.ApplyPreset(LivePresets.VC1IISSmoothStreamingLowBandwidthStandard);
PushBroadcastPublishFormat format = new PushBroadcastPublishFormat();
format.PublishingPoint = new Uri(PublishPoint);
job.PublishFormats.Add(format);
// Starts encoding
job.StartEncoding();
}
this code encode a list of files in a directory when he finish one he jump to the next
what I want to do is change the file name when it's encoded before passing to th other one
I have added this Methode I don't know if it work or no
public void liveJob_Status(object sender, EncodeStatusEventArgs e)
{
if (e.Status == EncodeStatus.Jumped)
{ LiveFileSource file = (LiveFileSource)e.LiveSource;
string name = file.Name;
string modified_name = "Encode" + name;
File.Move(DataDirectory + #"\" + name, DataDirectory + #"\" + name.Replace(name, modified_name));
}
}