I uploaded the document in SharePoint document library using CSOM. Now I need to Rename the uploaded file using CSOM, here is my code
Web web = context.Web;
bool iscontinue = false;
FileCreationInformation newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes(InputFileName);
newFile.Url = "/" + newFile;
List docs = web.Lists.GetByTitle(ConfigurationManager.AppSettings["DocumentLibraryName"]);
string strFilename = InputFileName;
//rename
List docs = web.Lists.GetByTitle("Shared Documents");
docs = web.Lists.GetByTitle(Convert.ToString(ConfigurationManager.AppSettings["DocumentLibraryName"]));
Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
context.Load(uploadFile);
context.ExecuteQuery();
ListItem item = uploadFile.ListItemAllFields;
string renamefile = txtfilename.Text.ToString();
string docTitle = string.Empty;
item["Title"] = renamefile;
item.Update();
RenameFile(context, strFilename, renamefile);
Related
I am working on SharePoint 2016 CSOM to get list item version history. unfortunately i am not getting the field values. please find the code below.
var file = item.File;
var versionFiles = file.Versions;
var fa = file.ListItemAllFields;
clientContext.Load(fa);
clientContext.Load(file);
clientContext.Load(versionFiles);
clientContext.ExecuteQuery();
if (null != versionFiles)
{
var fileVersion = file.Versions[5];
SP.File oldFile =web.GetFileByServerRelativeUrl("/sites/site/_vti_history/1234/list1/file1.pdf");
var allField = oldFile.ListItemAllFields;
clientContext.Load(allField);
}
You could get version history metadata from Lists.asmx.
Sample code:
var web = clientContext.Web;
List spList = clientContext.Web.Lists.GetByTitle("MyDoc");
var item = spList.GetItemById(43);
clientContext.Load(spList);
clientContext.Load(item);
clientContext.ExecuteQuery();
#region customList
Lists.Lists listService = new Lists.Lists();
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
listService.Url = siteUrl + "/_vti_bin/lists.asmx";
XmlNode nodeAttachments = listService.GetVersionCollection(spList.Id.ToString(), item.Id.ToString(), "Title");
foreach (System.Xml.XmlNode xNode in nodeAttachments)
{
Console.WriteLine(xNode.Attributes["Title"].Value);
}
I need to create subfolder in sharepoint with client object model, the parent folder is existing, this is my code, but I got this error,
Invalid file name.
The file name you specified could not be used. It may be the name of an existing file or directory, or you may not have permission to access the file.
ContentTypeCollection listContentTypes = list.ContentTypes;
clientContext.Load(listContentTypes, types => types.Include
(type => type.Id, type => type.Name,
type => type.Parent));
var result = clientContext.LoadQuery(listContentTypes.Where
(c => c.Name == "Folder"));
clientContext.ExecuteQuery();
ContentType folderContentType = result.FirstOrDefault();
ListItemCreationInformation newItem = new ListItemCreationInformation();
newItem.UnderlyingObjectType = FileSystemObjectType.Folder;
newItem.FolderUrl = #"http://mysite/sites/org" + "/" + listName;
if (!folderName1.Equals(string.Empty))
{
newItem.FolderUrl += "/" + folderName1;
}
newItem.LeafName = folderName2;
ListItem item = list.AddItem(newItem);
item["ContentTypeId"] = folderContentType.Id.ToString();
item["Title"] = folderName2;
item.Update();
clientContext.Load(list);
clientContext.ExecuteQuery();
If you need to create folder you can try to use the following code:
using (var clientContext = new ClientContext(#"http://server"))
{
var web = clientContext.Web;
var lst = web.Lists.GetByTitle("CheckDocLib");
var fld1 = lst.RootFolder.Folders.Add("FirstLevel1");
var fld2 = fld1.Folders.Add("SecondLevel1");
fld1.Update();
fld2.Update();
clientContext.ExecuteQuery();
}
I'm developing a rather simple visual WebPart for SharePoint Foundation Server 2010.
It's supposed to upload an image file to the SharePoint server and display it afterwards.
While I can successfully upload the file to a previously created document library, the file cannot be displayed (IE shows the red cross). When I upload an exact copy of the file using SharePoint frontend, it can be opened. I hope that someone can tell me what I'm missing.
Below you can find the code that successfully uploads a file to the server:
SPContext.Current.Web.AllowUnsafeUpdates = true;
string path = "";
string[] fileName = filePath.PostedFile.FileName.Split('\\');
int length = fileName.Length;
// get the name of file from path
string file = fileName[length - 1];
SPWeb web = SPContext.Current.Web;
SPFolderCollection folders = web.Folders;
SPFolder folder;
SPListCollection lists = web.Lists;
SPDocumentLibrary library;
SPList list = null;
Guid guid = Guid.Empty;
if (lists.Cast<SPList>().Any(l => string.Equals(l.Title, "SPUserAccountDetails-UserImages")))
{
list = lists["SPUserAccountDetails-UserImages"];
}
else
{
guid = lists.Add("SPUserAccountDetails-UserImages", "Enthält Mitarbeiter-Fotos", SPListTemplateType.DocumentLibrary);
list = web.Lists[guid];
}
library = (SPDocumentLibrary)list;
folder = library.RootFolder.SubFolders.Add("SPUserAccountDetails");
SPFileCollection files = folder.Files;
Stream fStream = filePath.PostedFile.InputStream;
byte[] MyData = new byte[fStream.Length];
Stream stream = new MemoryStream();
stream.Read(MyData, 0, (int)fStream.Length);
fStream.Close();
bool bolFileAdd = true;
for (int i = 0; i < files.Count; i++)
{
SPFile tempFile = files[i];
if (tempFile.Name == file)
{
folder.Files.Delete(file);
bolFileAdd = true;
break;
}
}
if (bolFileAdd)
{
SPFile f = files.Add(file, MyData);
f.Item["ContentTypeId"] = "image/jpeg";
f.Item["Title"] = file;
f.Item.SystemUpdate();
SPContext.Current.Web.AllowUnsafeUpdates = false;
imgPhoto.ImageUrl = (string)f.Item[SPBuiltInFieldId.EncodedAbsUrl];
}
Never mind. My code seems to mess with the file content. I'll post the solution later.
edit:
I'm stupid and sorry :-/
I replaced this:
Stream fStream = filePath.PostedFile.InputStream;
byte[] MyData = new byte[fStream.Length];
Stream stream = new MemoryStream();
stream.Read(MyData, 0, (int)fStream.Length);
fStream.Close();
with this:
Stream fStream = filePath.PostedFile.InputStream;
byte[] MyData = new byte[fStream.Length];
BinaryReader binaryReader = new BinaryReader(fStream);
MyData = binaryReader.ReadBytes((Int32)fStream.Length);
fStream.Close();
binaryReader.Close();
and suddenly it all worked ;-)
I am calling Sharepoint web service methond GetListItems, and don't see anything about file/folder size being returned. Am I missing something, or is there another way to get the size of the file/folder. Many thanks in advance.
the field you need is called ows_FileSizeDisplay, this returns an int for the number of bytes.
here is some code to put you on the rigth track
List<File> files = new List<File>(1);
File tempFile;
#region Get SharePointItems
SharePointListService.Lists svc = new SharePointListService.Lists();
XmlNode spItemsNode;
try
{
svc.Credentials = System.Net.CredentialCache.DefaultCredentials;
svc.Url = baseSharePointPath+"/_vti_bin/Lists.asmx";
XmlDocument xmlDoc = new System.Xml.XmlDocument();
XmlNode queryOptions =
xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
queryOptions.InnerXml = "<QueryOptions><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns><DateInUtc>TRUE</DateInUtc><Folder>" +
baseSharePointPath + "/"+ listName + "/"+ folderName + "</Folder></QueryOptions>";
XmlNode query =
xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
query.InnerXml = "<Where><Eq><FieldRef Name='Usage'/><Value Type='Text'>%%usage%%</Value></Eq></Where>";
query.InnerXml = query.InnerXml.Replace("%%usage%%", ConvertFileUsageToString(usage));
spItemsNode = svc.GetListItems(listName,
null, query, null, null, queryOptions, null);
}
finally
{
svc.Dispose();
}
// load the response into an xml document
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(spItemsNode.OuterXml);
// create a namespace manager
XmlNamespaceManager ns = new XmlNamespaceManager(xDoc.NameTable);
// add all the special SharePoint Namespaces in
ns.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
ns.AddNamespace("z", "#RowsetSchema");
ns.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/soap/");
ns.AddNamespace("s", "uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882");
ns.AddNamespace("dt", "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882");
XmlNodeList Items = xDoc.SelectNodes(#"/sp:listitems/rs:data/z:row", ns);
#endregion
foreach (XmlNode currentFile in Items)
{
tempFile = new File();
tempFile.Name = currentFile.Attributes["ows_NameOrTitle"].Value;
tempFile.Type = currentFile.Attributes["ows_DocIcon"].Value;
tempFile.Usage = ConvertToFileUsage(currentFile.Attributes["ows_Usage"].Value);
tempFile.Data = getFileBytes(currentFile.Attributes["ows_RequiredField"].Value, baseSharePointPath);
files
Here is a nice code snippet that will do the job shout if you have any questions
Folder folder = getFolder(serverRelitiveURL);
FileCollection files = folder.Files;
folder.Context.Load(files);
folder.Context.ExecuteQuery();
int folderSize;
foreach(file in files)
{
ListItem li = file.ListItemAllFields;
Console.writeline(li["File_x0020_Size"]);
folderSize = li["File_x0020_Size"]+folderSize;
}
Console.writeline(folderSize);
I have a SharePoint calendar event that can have any type of file as attachment. Is there any way to access the contents of the file/ download them? I have to calculate the check sum of these files.
string siteURL = "http://yourserver/yourpathtothesite";
using (SPSite site = new SPSite(siteURL))
{
using (SPWeb web = site.OpenWeb())
{
string listName = "Events";
SPList calendarList = web.Lists[listName];
// get whatever item you are interested in
SPListItem item = calendarList.GetItemById(1);
foreach (String attachmentname in item.Attachments)
{
String attachmentAbsoluteURL = item.Attachments.UrlPrefix + attachmentname;
// To get the SPSile reference to the attachment just use this code
SPFile attachmentFile = web.GetFile(attachmentAbsoluteURL);
// To read the file content simply use this code
Stream stream = attachmentFile.OpenBinaryStream();
StreamReader reader = new StreamReader(stream);
String fileContent = reader.ReadToEnd();
}
}
}
Source: http://www.dotnetking.com/TechnicalComments.aspx?LogID=352