Could not Delete image from directory using C# - c#-4.0

I am trying to delete an image from directory using following statement
System.IO.File.Delete(Path);
i have previously accessed this image in another function
Image image=Image.FromFile(imagePath)
imageList1.Images.Add(image);
but it shows an error that file is locked by another process. I searched for this and find out that I should use using to dispose of the image object so i tried this
using(Image image=Image.FromFile(imagePath))
imageList1.Images.Add(image);
but this gives me an error in program.cs that paramter is not valid and programs doesnot run.
and sometime it gives the error
Starting a second message loop on a single thread is not a valid operation. Use Form.ShowDialog instead.
I am adding the imagelist to a list view and before deleting the file i am clearing all the items of both imagelist and listview with following commands.
imageList1.Images.RemoveByKey(imageName);
imageList1.Images.Clear();
listView1.Items.RemoveByKey(imageName);
listView1.Items.Clear();
listView1.SmallImageList = null;
this is my code where i am populating listview.
try
{
string album = albumListBox.SelectedItem.ToString();
List<string> imageName=new List<string>();
XmlDocument doc = new XmlDocument();
doc.Load(Application.StartupPath + "/image.xml");
XmlNodeList list = null;
list = doc.SelectNodes(string.Format("/images/image"));
listView1.Columns.Clear();
listView1.Columns.Add("Image List",210,HorizontalAlignment.Left);
listView1.SmallImageList = imageList1;
listView1.Items.Clear();
imageList1.Images.Clear();
listView1.MultiSelect = false;
foreach (XmlNode node in list)
{
if (node.ChildNodes[2].InnerText == album)
{
string imagePath = Application.StartupPath + "\\images\\" + album + "\\" + node.ChildNodes[0].InnerText;
Image image = Image.FromFile(imagePath);
imageList1.Images.Add(image);
imageName.Add(node.ChildNodes[0].InnerText);
}
}
for (int j = 0; j < this.imageList1.Images.Count; j++)
{
listView1.Items.Add(imageName[j],imageName[j],j);
listView1.View = View.Details;
}
}
catch (Exception e)
{
MessageBox.Show("No Images in this Album Please add the Images");
showImage.Hide();
}
and this is the code where i want to delete the file
var listItem = listView1.SelectedItems[0];
string album = albumListBox.SelectedItem.ToString();
string imageName = listItem.Text;
string imagePath = Application.StartupPath + "\\images\\" + album + "\\" + imageName;
XmlDocument doc = new XmlDocument();
doc.Load(Application.StartupPath + "/image.xml");
XmlNode node = doc.SelectSingleNode(string.Format("//image[./imageName/text()='" + imageName + "' and ./album/text()='" + album + "']"));
if (node != null)
{
//remove image from directory tooV
doc.DocumentElement.RemoveChild(node);
doc.Save(Application.StartupPath + "/image.xml");
imageList1.Images.RemoveByKey(imageName);
imageList1.Images.Clear();
listView1.Items.RemoveByKey(imageName);
listView1.Items.Clear();
listView1.Items[listView1.SelectedIndices[0]].Remove();
imageList1.Images.RemoveAt(listView1.SelectedIndices[0]);
listView1.SmallImageList = null;
fillImageList();
System.IO.File.Delete(imagePath);
MessageBox.Show("Image deleted");
fillAlbumList();
}

So far as the image is still referenced in imagelist1, it is not disposed. In order to properly dispose it, you will have to dispose the imagelist1 also. Then only all the reference to Image are closed.

Related

Generate Text File Upon Button Action and Save to local Drive using Acumatica

I am trying to generate a text file on an Action Button, with contents of a dataview created in a Graph Class and Save the file in my Local Drive. But i am unable to do it.
Please help me with the file generation...Thanks
I AM USING Acumatica Version 2019R2 (v 19.203.0042)
MY CODE GOES HERE...
public PXSelect<MayBankGIRO> Document; //this is my dataview
public PXAction<MayBankGiroFilter> createTextFile;
[PXUIField(DisplayName = "Create Text File")]
[PXButton()]
public virtual IEnumerable CreateTextFile(PXAdapter adapter)
{
string filepath = "C:\\Subhashish Dawn";
System.IO.StreamWriter sw = new System.IO.StreamWriter(filepath);
MayBankGIRO giroObject = this.Document.Current;
List<object> myListObject = new List<object> { };
FixedLengthFile flatFile = new FixedLengthFile();
foreach (MayBankGIRO dacRecord in this.Document.Select())
{
if (giroObject.ReordType == "00")
{
myListObject.Add(dacRecord.ReordType + "|" + dacRecord.CorporateID + "|" + dacRecord.ClientBatchID + "|");
}
else
{
myListObject.Add(dacRecord.ReordType + "|" + dacRecord.CorporateID + "|" + dacRecord.ClientBatchID + "|" + dacRecord.Country + "|");
string data = dacRecord.ReordType;
}
this.Document.Update(dacRecord);
}
flatFile.WriteToFile(myListObject, sw);
sw.Flush();
sw.FlushAsync();
string path = "DAWN" + ".txt";
PX.SM.FileInfo file = new PX.SM.FileInfo(Guid.NewGuid(), path, null, System.Text.Encoding.UTF8.GetBytes(**path**)); // what shall i substitite in place of **path**
throw new PXRedirectToFileException(file, true);
}
``````````````````````````````````````````````````````
Can anyone please specify what changes in have to make in the above code.
I utilize UploadFileMaintenance to do this. I'm not sure if this will meet your needs, but here is the core of my code that works for me.
byte[] labelBytes = Encoding.ASCII.GetBytes(myLabelData);
if(labelBytes.Length > 0)
{
string filename = "label-" + Guid.NewGuid().ToString() + ".txt";
PX.SM.FileInfo labelFileInfo = new FileInfo(filename, null, labelBytes);
UploadFileMaintenance upload = PXGraph.CreateInstance<UploadFileMaintenance>();
if (upload.SaveFile(labelFileInfo))
{
string targetUrl = PXRedirectToFileException.BuildUrl(labelFileInfo.UID);
throw new PXRedirectToUrlException(targetUrl, "Print Labels");
}
}
Assuming your Document object is the view you need and its Select() method returns all the data records you need inside your file, this should work:
// We need at least these, listing them for reference
using PX.Data;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
// This is your dataview
public PXSelect<MayBankGIRO> Document;
// Your action delegate
public PXAction<MayBankGiroFilter> createTextFile;
[PXUIField(DisplayName = "Create Text File")]
[PXButton()]
public virtual IEnumerable CreateTextFile(PXAdapter adapter)
{
// You can use this method to print debug information for your customizations
// Just remove when you are done testing
PXTrace.WriteInformation("Generating records");
// We will build the content as a string list first
List<string> myList = new List<string> { };
// If the value of 'ReordType' can change for each record, you don't need this
MayBankGIRO giroObject = this.Document.Current;
foreach (MayBankGIRO dacRecord in this.Document.Select())
{
// Does 'ReordType' change for each record?
// if it does you may need to use 'dacRecord.ReordType' in this if instead
if (giroObject.ReordType == "00")
{
// This only works if all these members are strings or can be cast to strings
myList.Add(dacRecord.ReordType + "|" + dacRecord.CorporateID + "|" + dacRecord.ClientBatchID + "|");
}
else
{
// This only works if all these members are strings or can be cast to strings
myList.Add(dacRecord.ReordType + "|" + dacRecord.CorporateID + "|" + dacRecord.ClientBatchID + "|" + dacRecord.Country + "|");
}
}
PXTrace.WriteInformation("Generating file");
// Set the name
string filename = "DAWN" + ".txt";
// Use our download method
Download(myList, filename);
}
// We can define a static method to be able to reuse this later for other DACs
public static void Download(List<string> lines, string name)
{
var bytes = default(byte[]);
// Write all lines to stream
using (MemoryStream stream = new MemoryStream())
{
StreamWriter sw = new StreamWriter(stream);
foreach (string line in lines)
{
sw.WriteLine(line);
}
sw.Close();
stream.Position = 0;
bytes = stream.ToArray();
};
// Save content to file object
PX.SM.FileInfo textDoc = new PX.SM.FileInfo(name, null, bytes);
if (textDoc != null)
{
// Trigger file download
throw new PXRedirectToFileException(textDoc, true);
} else {
//TODO: You could raise an exception here also to notify the user
PXTrace.WriteInformation("Could not generate file");
}
}
Hi Markoan your code helped me to create the textfile but the content of the textfile is getting repeated with the first record of the data-view. My reord type have only three values "00" for the first record "01" for the 2nd to n-1 record and "99" for the nth record.
Though I have made few changes to your code
// We need at least these, listing them for reference
using PX.Data;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
// This is your dataview
public PXSelect<MayBankGIRO> Document;
// Your action delegate
public PXAction<MayBankGiroFilter> createTextFile;
[PXUIField(DisplayName = "Create Text File")]
[PXButton()]
public virtual IEnumerable CreateTextFile(PXAdapter adapter)
{
// You can use this method to print debug information for your customizations
// Just remove when you are done testing
PXTrace.WriteInformation("Generating records");
// We will build the content as a string list first
List<string> myList = new List<string> { };
// If the value of 'ReordType' can change for each record, you don't need this
MayBankGIRO giroObject = this.Document.Current;
foreach (MayBankGIRO dacRecord in this.Document.Select())
{
// Does 'ReordType' change for each record?
// if it does you may need to use 'dacRecord.ReordType' in this if instead
myList.Add(dacRecord.ReordType + "|" + dacRecord.CustomerReferenceNumber + "|" + dacRecord.ClientBatchID + "|" + dacRecord.Country + "|");
}
PXTrace.WriteInformation("Generating file");
// Set the name
string filename = "DAWN" + ".txt";
// Use our download method
Download(myList, filename);
}
// We can define a static method to be able to reuse this later for other DACs
public static void Download(List<string> lines, string name)
{
var bytes = default(byte[]);
// Write all lines to stream
using (MemoryStream stream = new MemoryStream())
{
StreamWriter sw = new StreamWriter(stream);
foreach (string line in lines)
{
sw.WriteLine(line);
}
// sw.Close(); this was showing some error
stream.Position = 0; // "Cannot reach a closed stream" hence i added it in the next line
bytes = stream.ToArray();
sw.Close();
};
// Save content to file object
PX.SM.FileInfo textDoc = new PX.SM.FileInfo(name, null, bytes);
if (textDoc != null)
{
// Trigger file download
throw new PXRedirectToFileException(textDoc, true);
} else {
//TODO: You could raise an exception here also to notify the user
PXTrace.WriteInformation("Could not generate file");
}
}

Compare two text files but one doesn't exist due to permissions

I am attempting to compare two text files in a Script Task in an SSIS Package. Both files exist in the file system. Both files are in the same directory. However, one does not exist because the permissions setup do not see the file.
The code below is not working. I have tried a few different variations of the code below and the SSIS Package continues to go forward, ultimately failing on a subsequent File System Task because doesn't have access to the file.
I am attempting to capture that the file is not present because the package does not have access to the file, and not because the file isn't there. Originally, I was using File.Exists(), however, that won't work because it returns false whether the file is not there or the package does not have access to it.
string packageName = Dts.Variables["System::PackageName"].Value.ToString();
string taskName = Dts.Variables["System.TaskName"].Value.ToString();
string inputFilePath = Dts.Variables["User::inputFilePath"].Value.ToString();
string processedFilePath = Dts.Variables["User::processedFilePath"].Value.ToString();
bool blnFilesMatch = true;
try
{
int i = 0, j = 0;
// Compare the source and processed files to determine if the contents are different.
using (var f1 = new FileStream(inputFilePath, FileMode.Open))
using (var f2 = new FileStream(processedFilePath, FileMode.Open))
{
do
{
i = f1.ReadByte();
j = f2.ReadByte();
if (i != j)
break;
} while (i != -1 && j != -1);
if (i != j)
blnFilesMatch = false; // Files Differ
else
blnFilesMatch = true; // Files are the same
}
Dts.Variables["User::blnIdenticalFiles"].Value = blnFilesMatch;
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (FileNotFoundException)
{
string tempFileName = "temp_" + packageName + ".txt.";
string tempFilePath = Path.Combine(Path.GetDirectoryName(inputFilePath), tempFileName);
// A file wasn't found. Try to create and delete a temp file to determine whether it was because of permissions or if the file just was not present.
try
{
File.Create(tempFilePath);
File.Delete(tempFilePath);
Dts.Variables["User::blnIdenticalFiles"].Value = false;
}
catch (UnauthorizedAccessException uae)
{
// Permissions cannot create the file.
Dts.Events.FireError(0, packageName + " - " + taskName, uae.Message, string.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
catch (Exception ex)
{
Dts.Events.FireError(0, packageName + " - " + taskName, ex.Message, string.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}

Why does this code return a value two times?

I made a code to copy over files and then it has to return the path of the copied folder but it returns a value twice!?
Also it shows the MessageBox twice and it executes SaveData also twice!?
Why does this happen??
public string Copy(string sourceDir, string targetDir)
{
System.IO.Directory.CreateDirectory(targetDir);
foreach (var file in System.IO.Directory.GetFiles(sourceDir))
System.IO.File.Copy(file, System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(file)));
foreach (var directory in System.IO.Directory.GetDirectories(sourceDir))
Copy(directory, System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(directory)));
XML_INFO info = new XML_INFO();
info.xmlIDCode = (tmpPluginNumberID.ToString());
SaveData(info, targetDir + #"\" + tmpPluginName + ".xml");
System.IO.File.Delete(Environment.CurrentDirectory + #"\GameData\" + tmpPluginName + ".xml");
MessageBox.Show(System.IO.Directory.GetParent(targetDir + #"\aFile.xml").ToString());
return targetDir;
}
this code is called from here :
private void COPY_TO_GAME_BUTTON_Click(object sender, EventArgs e)
{
foreach (var v in listView1.SelectedItems)
{
ListViewItem lvi = ((ListViewItem)v);
tmpPluginNumberID = int.Parse(lvi.SubItems[4].Text);
tmpPluginName = lvi.Text;
string sourceDir = lvi.SubItems[1].Text;
DialogResult dr = MessageBox.Show("Do you want to copy the selected plugin to GameData?" + Environment.NewLine + "By clicking 'no' the plugin will be copied to the root of the game." + Environment.NewLine + "Note that only plugins copied to GameData are supported with Stats and Update data.", "How do we install?", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dr == DialogResult.Yes)
{
lvi.SubItems[3].Text = "Imported to GameData";
lvi.SubItems[2].Text = Copy(sourceDir, Environment.CurrentDirectory + #"\GameData");
saveXML(lvi.Text, lvi.SubItems[1].Text,lvi.SubItems[2].Text, lvi.SubItems[3].Text, lvi.SubItems[4].Text, true);
}
else if (dr == DialogResult.No)
{
Copy(sourceDir, Environment.CurrentDirectory + #"\");
lvi.SubItems[2].Text = "GameData path is unavailable when copied to root the game.";
lvi.SubItems[3].Text = "Stats are unavailable when copied to root the game";
saveXML(lvi.Text, lvi.SubItems[1].Text, lvi.SubItems[2].Text, lvi.SubItems[3].Text, lvi.SubItems[4].Text, true);
}
else
{
}
}
}
AHA I found it I called the function also inside the function to fix it I made this function :
public void CopyPhaseTwo(string sourceDir, string targetDir)
{
System.IO.Directory.CreateDirectory(targetDir);
foreach (var file in System.IO.Directory.GetFiles(sourceDir))
System.IO.File.Copy(file, System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(file)));
foreach (var directory in System.IO.Directory.GetDirectories(sourceDir))
Copy(directory, System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(directory)));
}

Sharepoint: How to upload files with metadata including Taxonomy fields through web services

Being very new to SharePoint coding I have been assigned the task to create a prototype code to upload a file and setting the field values for that file that will show up when opening the sharepoint page with the file.
This has to be done from a remote machine and not the Sharepoint server itself so using the .Net objects for Sharepoint is out the question.
I quickly found out how to upload a file through the Sharepoint Web Service Copy.asmx:
void UploadTestFile() {
var file = #"C:\Temp\TestFile.doc";
string destinationUrl = "http://mysharepointserver/Documents/"
+ Path.GetFileName(file);
string[] destinationUrls = { destinationUrl };
var CopyWS = new Copy.Copy();
CopyWS.UseDefaultCredentials = true;
CopyWS.Url = "http://mysharepointserver/_vti_bin/copy.asmx";
CopyResult[] result;
byte[] data = File.ReadAllBytes(file);
FieldInformation mf1 = new FieldInformation {
DisplayName = "title",
InternalName = "title",
Type = FieldType.Text,
Value = "Dummy text"
};
FieldInformation mf2 = new FieldInformation {
DisplayName = "MyTermSet",
InternalName = "MyTermSet",
Type = FieldType.Note,
Value = "Test; Unit;"
};
CopyWS.CopyIntoItems(
"+",
destinationUrls,
new FieldInformation[] { mf1, mf2 },
data,
out result);
}
This code easily uploads any file to the target site but only fills the "title" field with info. The field MyTermSet in which I have added 3 terms allready - Test, Unit and Page - will not update with the values "Test;" and "Unit;".
Being very new to Sharepoint and me not grasping all the basics googling has told me that updating "File", "Computed" or "Lookup" fields does not work with the CopyIntoItems method, and MyTermSet being a Taxonomy field is - if I am correct - a Lookup field.
So how do I get MyTermSet updated with the values "Test;" and "Unit;" ?
I would really prefer If someone has a sample code on this. I have followed several hint-links but I am none the wiser. I have found no sample-code on this at all.
Have anyone made one single method that wraps it all? Or another method that takes in the destinationUrl from the file upload and updates the Term Set/Taxonomy field.
Puzzling together what I have found so far, I am now able to do as I wanted. But I would really like to be able to get the Taxonomy field GUIDs dynamically and NOT having to explicitly set them myself:
void UploadTestFile(string FileName, string DocLib, Dictionary<string, string> Fields = null) {
//Upload the file to the target Sharepoint doc lib
string destinationUrl = DocLib + Path.GetFileName(FileName);
string[] destinationUrls = { destinationUrl };
var CopyWS = new Copy.Copy();
CopyWS.UseDefaultCredentials = true;
CopyWS.Url = new Uri(new Uri(DocLib), "/_vti_bin/copy.asmx").ToString();
CopyResult[] result;
var data = File.ReadAllBytes(FileName);
CopyWS.CopyIntoItems(
"+",
destinationUrls,
new FieldInformation[0],
data,
out result);
if (Fields == null) return; //Done uploading
//Get the ID and metadata information of the fields
var list = new ListsWS.Lists();
list.UseDefaultCredentials = true;
var localpath = new Uri(DocLib).LocalPath.TrimEnd('/');
var site = localpath.Substring(0, localpath.LastIndexOf("/")); //Get the site of the URL
list.Url = new Uri(new Uri(DocLib), site + "/_vti_bin/lists.asmx").ToString(); //Lists on the right site
FieldInformation[] fiOut;
byte[] filedata;
var get = CopyWS.GetItem(destinationUrl, out fiOut, out filedata);
if (data.Length != filedata.Length) throw new Exception("Failed on uploading the document.");
//Dictionary on name and display name
var fieldInfos = fiOut.ToDictionary(x => x.InternalName, x => x);
var fieldInfosByName = new Dictionary<string, FieldInformation>();
foreach (var item in fiOut) {
if (!fieldInfosByName.ContainsKey(item.DisplayName)) {
fieldInfosByName.Add(item.DisplayName, item);
}
}
//Update the document with fielddata - this one can be extended for more than Text and Note fields.
if (!fieldInfos.ContainsKey("ID")) throw new Exception("Could not get the ID of the upload.");
var ID = fieldInfos["ID"].Value; //The ID of the document we just uploaded
XDocument doc = new XDocument(); //Creating XML with updates we need
doc.Add(XElement.Parse("<Batch OnError='Continue' ListVersion='1' ViewName=''/>"));
doc.Element("Batch").Add(XElement.Parse("<Method ID='1' Cmd='Update'/>"));
var methNode = doc.Element("Batch").Element("Method");
//Add ID
var fNode = new XElement("Field");
fNode.SetAttributeValue("Name", "ID");
fNode.Value = ID;
methNode.Add(fNode);
//Loop each field and add each Field
foreach (var field in Fields) {
//Get the field object from name or display name
FieldInformation fi = null;
if (fieldInfos.ContainsKey(field.Key)) {
fi = fieldInfos[field.Key];
}
else if (fieldInfosByName.ContainsKey(field.Key)) {
fi = fieldInfosByName[field.Key];
}
if (fi != null) {
//Fix for taxonomy fields - find the correct field to update
if (fi.Type == FieldType.Invalid && fieldInfos.ContainsKey(field.Key + "TaxHTField0")) {
fi = fieldInfos[field.Key + "TaxHTField0"];
}
else if (fi.Type == FieldType.Invalid && fieldInfosByName.ContainsKey(field.Key + "_0")) {
fi = fieldInfosByName[field.Key + "_0"];
}
fNode = new XElement("Field");
fNode.SetAttributeValue("Name", fi.InternalName);
switch (fi.Type) {
case FieldType.Lookup:
fNode.Value = "-1;#" + field.Value;
break;
case FieldType.Choice:
case FieldType.Text:
fNode.Value = field.Value;
break;
case FieldType.Note: //TermSet's
var termsetval = "";
var terms = field.Value.Split(';');
foreach (var term in terms) {
termsetval += "-1;#" + term + ";";
}
fNode.Value = termsetval.TrimEnd(';');
break;
default:
//..Unhandled type. Implement if needed.
break;
}
methNode.Add(fNode); //Adds the field to the XML
}
else {
//Field does not exist. No use in uploading.
}
}
//Gets the listname (not sure if it is the full path or just the folder name)
var listname = new Uri(DocLib).LocalPath;
var listcol = list.GetListCollection(); //Get the lists of the site
listname = (from XmlNode x
in listcol.ChildNodes
where x.Attributes["DefaultViewUrl"].InnerText.StartsWith(listname, StringComparison.InvariantCultureIgnoreCase)
select x.Attributes["ID"].InnerText).DefaultIfEmpty(listname).First();
//Convert the XML to XmlNode and upload the data
var xmldoc = new XmlDocument();
xmldoc.LoadXml(doc.ToString());
list.UpdateListItems(listname, xmldoc.DocumentElement);
}
Then I call it like this:
var fields = new Dictionary<string, string>();
fields.Add("Test", "Dummy Text");
fields.Add("MrTermSet", "Page|a4ba29c1-3ed5-47e9-b43f-36bc59c0ea5c;Unit|4237dfbe-22a2-4d90-bd08-09f4a8dd0ada");
UploadTestFile(#"C:\Temp\TestFile2.doc", #"http://mysharepointserver/Documents/", fields);
I would however prefer to call it like this:
var fields = new Dictionary<string, string>();
fields.Add("Test", "Dummy Text");
fields.Add("MrTermSet", "Page;Unit");
UploadTestFile(#"C:\Temp\TestFile2.doc", #"http://mysharepointserver/Documents/", fields);

Get file/folder size from sharepoint using GetListItems

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);

Resources