Display properties of an XML file using XmlTextWriter - c#

I have created an xml file using the following code:
XmlTextWriter write = new XmlTextWriter(FileName, null);
write.Formatting = Formatting.Indented;
write.WriteStartDocument();
write.WriteComment("Its Xml Document");
write.WriteStartElement("CollegeInformation");
write.WriteStartElement("StudentDetails");
write.WriteElementString("stdID", "1001");
write.WriteElementString("StudentName", "XYZ");
write.WriteEndElement();
write.WriteEndElement();
write.WriteEndDocument();
write.Close();
Now I want to display the properties of this xml file like name, file size, length on console.
How can I do that ?

Use can use FileInfo class to get the file properties.
System.IO.FileInfo f = new System.IO.FileInfo(FileName);
Console.WriteLine("The size of {0} is {1} bytes.", f.Name, f.Length);
Click on below link to get the properties available with the FileInfo Class.
http://msdn.microsoft.com/en-us/library/system.io.fileinfo_properties%28v=vs.110%29.aspx

Related

C#. Writing settings to XML file

I have some names of files. I am creating a XML file to store them. When application runs second time it should recognize those file names. Here is my code:
XmlWriter writer = XmlWriter.Create("settings.xml");
writer.WriteStartElement("DialogCreater");
writer.WriteElementString("conditionsFile", conditionsFile);
writer.WriteEndElement();
writer.Close();
But when I use those file names like this:
string[] lines = File.ReadAllLines(charactersFile);
It gives me an error.
System.NotSupportedException
Here how I read them from XML file:
XmlDocument doc = new XmlDocument();
doc.Load("settings.xml");
XmlNodeList node = doc.GetElementsByTagName("files");
foreach (XmlNode n in node[0].ChildNodes)
{
if (n.Name == "conditionsFile") conditionsFile = n.InnerText;
}
NotSupportedException
path is in an invalid format according to msdn documentation. you can fix it by checking path exist or not before reading from itMore info
string path = #"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
//file exist
}

How can I save the attribute named "x:SynchronousMode" to a xaml file?

In our software, we can draw or edit shapes and save it as a xaml.
Then, we want to load it(this xaml file) asynchronously, we used LoadAsync() method to do this, now the question is we can write x:SynchronousMode='Async' to the file manually, but how can we save this attribute to a xaml file directly(when we serialize it)?
The instruction from MSDN:
In order for LoadAsync to load XAML input asynchronously, the root
element in the XAML input must contain the attribute and value
x:SynchronousMode="Async".
Finally,I didn't find the way to add the attribute to the object, then I used a tack-handed way to solve this problem by the following code:
StringBuilder sb = new StringBuilder();
var xmlWriter = XmlWriter.Create(sb, settings);
XamlWriter.Save(Window, xmlWriter);
var str = sb.ToString().Insert(11, "assembly:SynchronousMode=\"Async\" ");
if (!File.Exists(path))
{
FileStream tmp = File.Create(path);
tmp.Close();
}
FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(str);
sw.Flush();
sw.Close();
fs.Close();
Insert it to the string that we convert object into with XamlWriter directly, and then save the string as a xaml file.

Add (xml) file to a .xlsx file and keep after 'save as'

Hi I have a need to store some data in a excel file (.xlsx) so I can send the file to our customers and extract data from it again later when they send us the file back to update some content.
The customer should not be able to see the data we store in the file, and certainly not be able to remove it (accidentally). In fact he should not be aware of it in any way. Also we want to add this info from a service on a system that doesn't have Excel installed.
I know that a .xlsx file is basicaly a zip file so I can extract the data and add a file to it, zip it again and have a valid file that can be opened by Excel. Only problem here is that after saving that file in Excel my custom xml file is removed from the package. So I need to know how to fix this.
What I have:
XNamespace MyNamespace = "http://stackoverflow.com/questions/ask";
XNamespace ExcelNamespace = "http://schemas.openxmlformats.org/package/2006/relationships";
string ExtractionPath = #"C:\temp\test\";
string ExcelFile = #"C:\temp\example.xlsx";
Directory.CreateDirectory(ExtractionPath);
System.IO.Compression.ZipFile.ExtractToDirectory(ExcelFile, ExtractionPath);
var Root = new XElement(MyNamespace + "tracker",
new XAttribute("version", "1.0.0.1"),
new XElement("connections"));
var file = Path.Combine(ExtractionPath, "connectioninfo.xml");
if (!File.Exists(file))
{
var relsPath = Path.Combine(ExtractionPath, "_rels", ".rels");
var rels = XElement.Load(relsPath);
rels.Add(new XElement(ExcelNamespace + "Relationship",
new XAttribute("Id", "XXXX"),
new XAttribute("Type", "http://schemas.openxmlformats.org/officeDocument/2006/relationships/customXml"),
new XAttribute("Target", "connectioninfo.xml")));
rels.Save(relsPath);
}
Root.Save(file);
if (File.Exists(ExcelFile)) File.Delete(ExcelFile);
System.IO.Compression.ZipFile.CreateFromDirectory(ExtractionPath, ExcelFile, System.IO.Compression.CompressionLevel.NoCompression, false);
When I run this code I end up with a file that contains my connectioninfo.xml file and that I can open in Excel. But when I save that file in excel and unzip the package again, then the connectioninfo.xml file is gone.
So question -> what am I missing to keep the file in the package after saving?
PS: I have also tried following code, but same problem ...
(using System.IO.Packaging;)
using (Package package = Package.Open(ExcelFile, FileMode.Open, FileAccess.ReadWrite))
{
Uri uriPartTarget = new Uri("/customXml/example.xml", UriKind.Relative);
if (!package.PartExists(uriPartTarget))
{
PackagePart customXml = package.CreatePart(uriPartTarget,
"application/vnd.openxmlformats-officedocument.customXmlProperties+xml");
using (Stream partStream = customXml.GetStream(FileMode.Create,
FileAccess.ReadWrite))
{
var doc = new XElement("test", new XElement("content","Hello world!"));
doc.Save(partStream);
}
}
}

How to edit a file in IsolatedStorage C#

I have been fiddling with this problem for the past hour so I thought you guys may be able to help on a Friday afternoon!
Problem
I am trying to edit an XML file in localstorage but can't figure out how to edit the existing file and re-save the file. The edit I have made it to remove a certain node from the XML.
Code
Here is the method that does all the work.
This first code snippet was already in the code and basically creates the XML file and saves it to localstorage.:
protected byte[] CreateFileData(PortableBusinessObjects.Location location, string geoObjectFilename)
{
byte[] fileData = null;
var xmlFile = System.IO.Path.GetFileNameWithoutExtension(geoObjectFilename) + ".xml";
var zipFile = System.IO.Path.GetFileNameWithoutExtension(geoObjectFilename) + ".zip";
using (IsolatedStorageFileStream fileStream = localStorage.CreateFile(xmlFile))
{
XmlWriter writer = XmlWriter.Create(fileStream);
if (location.GetType() == typeof(PortableBusinessObjects.Shape))
_xmlShapeSerializer.Serialize(writer, location);
else if (location.GetType() == typeof(PortableBusinessObjects.Point))
_xmlPointSerializer.Serialize(writer, location);
fileStream.Flush();
fileStream.Close();
}
}
This is my attempt at overwriting the saved file (Doesn't work):
using (IsolatedStorageFileStream doc = localStorage.OpenFile(xmlFile, FileMode.Open))
{
System.Xml.Linq.XDocument test = System.Xml.Linq.XDocument.Load(doc);
test.Descendants("Time").Remove();
XmlWriter writer = XmlWriter.Create(doc);
doc.Flush();
doc.Close();
}
Question
Where do I place my code that removes the "Time" nodes and saves the file?
Your saving code doesn't do any saving - you just create an XmlWriter and do nothing with it.
There are various methods built into XDocument than can help you here. While you could pass your XmlWriter to it, you can actually save directly to the stream:
test.Save(doc);
Note you will need to move to the beginning of the stream before writing to it - loading your XML will have read to the end:
doc.Position = 0;
You should use the IsolatedStorageFileStream together with the StreamWriter.
See How to: Read and Write to Files in Isolated Storage
With XDocument you then have to Save() the new contents to the stream.

XMLWriter issues in C#

My issue is that I can't have the XML's file name be saved based on the text of a given field: here is the line:
XmlTextWriter writer = new XmlTextWriter(#"{0}\ops\op-" + OpName.Text.Replace(" ", "_") + ".xml",
System.Text.Encoding.UTF8);
The issue I get is that it can't find the path: C:\[stuff]\{0}\op\op-.xml and if I remove the {0}(in the code) I get can't find C:\op\op-.xml
I am needing it to find C:\[stuff]\op\ so it can make the file in that folder.
How could I change this line?
What does {0} represents in your path? XmlTextWriter constructor takes file path, not a formatted string. It would be much more readable if you'd prepare your file path in steps, eg. by utilizing Path.Combine method:
var fileName = string.Format("op-{0}.xml", OpName.Text.Replace(" ", "_"));
var rootDir = /* this would be {0} from your original example */
var filePath = Path.Combine(rootDir, "ops", fileName);
XmlTextWriter writer = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
string additionalStr=OpName.Text.Replace(" ", "_");
if (string.IsNullOrEmpty(additionalStr))
{
return;
//or throw error or make default file name depending on the required logic
}
string directoryPath=String.Format(#"{0}\ops\",dirPrefix);
bool isDirectoryExists=Directory.Exists(directoryPath);
if (!isDirectoryExists){
//required logic. for example set default directory
}
string fileName=additionalStr+".xml";
string filePath=Path.Combine(directoryPath,fileName);
XmlTextWriter writer = new XmlTextWriter(filePath,System.Text.Encoding.UTF8);

Categories