Use local file with StringReader - c#

I'm developing an app for WP.
I'm using a XML file online, it's working fine but when I want to use the same XML file in local storing, this doesn't work...
I added it at my project.
To use it online, I'm using that :
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri("http://exemple.com/news.xml"), "News");
And in my function client_DownloadStringCompleted, I read like that:
StringReader stringReader = new StringReader(e.Result);
So this it's working but with my local file I'm doing like that directly and it's not working :
StringReader stringReader = new StringReader("news.xml");
Do you know how I can fix that ?
Thank you for your help.
EDIT :
It's ok, thanks for your help !
I wrote that :
var resource = Application.GetResourceStream(new Uri(#"/YOURASSEMBLYNAME;component/news.xml", UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream);
StringReader stringReader = new StringReader(streamReader.ReadToEnd());
And I used the file like a resource.

The parameter of the StringReader constructor is the string that you want to read.
In the code that you have that does not work, you are reading the name of the file not the contents of the file.

Related

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.

Simple client server to send XML information to CRUD database

I need to develop a resident app to get info from Win32_BaseBoard class when is required by another app by XML without create any file and then this app must insert or update that information on database.
I saw a few apps but always have to create a file and i don't know if already exists something like that.
The code below will create memory stream with the data instead of writing to a file.
///old code
//XmlSerializer serializer = new XmlSerializer(typeof(AppConfig));
//StreamWriter writer = new StreamWriter(FILENAME);
//serializer.Serialize(writer, config);
//new code
string input = "Your XML here";
string output = "";
XmlSerializer serializer = new XmlSerializer(typeof(AppConfig));
MemoryStream mstream = new MemoryStream(Encoding.UTF8.GetBytes(input));
StreamWriter writer = new StreamWriter(mstream);
serializer.Serialize(writer, config);
​

How to read XML document and display the output as string in c#

consider my source file looks like this.
<Content xmlns="uuid:4522eb85-0a47-45f9-8e2b-1x82c78xx920">
<first>Hello World.This is Fisrt field</first>
<second>Hello World.This is second field</second>
</Content>
I want to write a code, which read this xml document from a location and display it as string.
say name of the xml file is helloworld.xml.
Location: D:\abcd\cdef\all\helloworld.xml.
I have tried the following, but i was unable to do it.
XmlDocument contentxml = new XmlDocument();
contentxml.LoadXml(#"D:\abcd\cdef\all\helloworld.xml");
Response.Write("<BR>" + contentxml.ToString());
Response.write is displaying nothing. Correct me if i missed any thing. Its not creating any component and error is coming.
I have also tried this,
XmlDocument contentxml = new XmlDocument();
try
{
contentxml.LoadXml(#"D:\abcd\cdef\all\helloworld.xml");
}
catch (XmlException exp)
{
Console.WriteLine(exp.Message);
}
StringWriter sw = new StringWriter();
XmlTextWriter xw = new XmlTextWriter(sw);
contentxml.WriteTo(xw);
Response.Write("<BR>" + sw.ToString());
But i did not find the any output.
I want to read a XML file from a location and display it as it is as string.
Can anyone help on this.
Thank you,
Muzimil.
You need the OuterXml property:
Response.Write("<BR>" + contentxml.OuterXml);
Also you are loading a file not xml so use
contentxml.Load(#"D:\abcd\cdef\all\helloworld.xml");
instead of
contentxml.LoadXml(#"D:\abcd\cdef\all\helloworld.xml");
Do you really have to deserialize the XML at all? Why not just read it as a text file? Something like..
String text = File.ReadAllText(#"D:\abcd\cdef\all\helloworld.xml");
Response.Write(text);
With appropriate error handling obviously..
I would try using the XDocument class:
//load the document from file
var doc = XDocument.Load("..."); //== path to the file
//write the xml to the screen
Response.Write(doc.ToString());
If you want to use an XmlDocument instead, you would want to use Load instead LoadXml.
If you want to simply write a file to the output, you can do Response.WriteFile.
try this
XmlTextReader reader = new XmlTextReader (#"D:\abcd\cdef\all\helloworld.xml");
while (reader.Read())
{
Console.WriteLine(reader.Name);
}
Console.ReadLine();
String text = File.ReadAllText(Server.MapPath("~/App_Data/sample.xml"));
txtData.Text = text;

serialize to XML path issue

I am trying to serialize my Report class info to an XML. At this point I think all of the serialize and deserialize code works, but for the initial write, I'm having trouble performing the serialize, because the XML file doesn't exist yet.
for an empty text file, i can use:
StreamWriter sw = File.CreateText(#"path");
sw.Close();
this is my code block for the serializing. the exception (Directory not found) is getting thrown on the StreamWriter line. I'd like to simply add an if(!File.Exists(xmlPath))...create empty XML. Or maybe there is a more correct way to do this.
public void SerializeToXML(Report newReport)
{
XmlSerializer serializer = new XmlSerializer(typeof(Report));
TextWriter textWriter = new StreamWriter(xmlPath);
serializer.Serialize(textWriter, newReport);
textWriter.Close();
}
The StreamWriter(String) constructor will create the file if it does not already exist:
If the file exists, it is overwritten; otherwise, a new file is created.
However, it will not create any inexistent directories in your path.
DirectoryNotFoundException: The specified path is invalid, such as being on an unmapped drive.
To create any required directories, you can include the following code (at the beginning of your SerializeToXML method):
var dir = Path.GetDirectoryName(xmlPath);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
First to make sure the directory exist you can use:
Directory.CreateDirectory(#"c:\directory\subdirectory");
You don't have to check if directory already exist.
A easy way to convert public classes to XML is to use the following snippet:
public static string ToXml<T>(T obj)
{
using (var ms = new MemoryStream())
using (var sr = new StreamReader(ms))
{
var xmlSer = new XmlSerializer(typeof(T));
xmlSer.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
return sr.ReadToEnd();
}
}
Then you could just use the following code to write it to a file:
var xmlString = Util.ToXml(report);
File.WriteAllText(#"path", xmlString);
(this example is without error handling)
Also, in your code you forgot to close/dispose the TextWriter. I would recommend using the using-statement to handle it for you.
CreateText, and the StreamWriter, will create files if they don't exist, but they won't create directories that don't already exist for you. Is your path correct?
Try Checking with a Directory.Exists(Path.GetDirectoryName(xmlPath)).

How to write a text file after the previous line in C#?

My below code creates a txt file and writes something to that file. But I need to write a new line after the previous lines when I run the script several times. Code:
string filePath = "D:\\DOT_NET\\C#\\abc.txt";
FileInfo t = new FileInfo(filePath);
StreamWriter Tex = t.CreateText();
Tex.WriteLine("Hi freinds");
Tex.WriteLine("csharpfriends is the new url for c-sharp");
Tex.Write(Tex.NewLine);
Tex.Close();
Current output on the abc.txt file:
Hi friends
csharpfriends is the new url for c-sharp
But I need the output if I run the script several times to be this:
Hi friends
csharpfriends is the new url for c-sharp
Hi friends
csharpfriends is the new url for c-sharp
Hi friends
csharpfriends is the new url for c-sharp
How can I do that? Please help.
StreamWriter has a constructor which lets you append text instead of just writing into the file. The constructor is
new StreamWriter(string filepath, bool append)
If you set that bool to "true", then all writing will be at the end of the document. In your example...
StreamWriter Tex = new StreamWriter(#"D:\DOT_NET\C#\abc.txt", true);
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("...");
}
Try this:
System.IO.File.WriteAllText(#"file_location", System.IO.File.ReadAllText(#"file_location") + System.Environment.NewLine + "The_new_text");
That will add a new text to the next line.

Categories