I'm trying to read an XML file in a C# WinRt app when the app resumes:
Windows.Storage.StorageFile File = await Windows.Storage.ApplicationData.Current.TemporaryFolder.GetFileAsync("PreviousSession.xml");
if (File != null)
{
var File2 = await Windows.Storage.ApplicationData.Current.TemporaryFolder.GetFileAsync("PreviousSession.xml");
string Document = File2.ToString();
System.Xml.Linq.XDocument.Parse(Document);
}
But I get a System.Xml.XmlException:
Data at the root level is invalid. Line 1, position 1.
How can I fix this and read the file properly?
My XML document is being constructed like this:
Windows.Data.Xml.Dom.XmlDocument Document = new Windows.Data.Xml.Dom.XmlDocument();
Windows.Data.Xml.Dom.XmlElement Element = (Windows.Data.Xml.Dom.XmlElement)Document.AppendChild(Document.CreateElement("PreviousSessionData"));
...
Windows.Storage.IStorageFile TempFile = await Windows.Storage.ApplicationData.Current.TemporaryFolder.CreateFileAsync("PreviousSession.xml", Windows.Storage.CreationCollisionOption.ReplaceExisting);
await Document.SaveToFileAsync(TempFile);
For a file like this:
<PreviousSessionData>...</PreviousSessionData>
System.Xml.Linq.XDocument.Parse expects an XML string, not an XML File name.
This code is wrong (see comments) :
string Document = File2.ToString(); // Return the name of "File2" object, not File2 content!
System.Xml.Linq.XDocument.Parse(Document); // Parse error, trying to parse the string "PreviousSession.xml" !
What you want is put the content of the file in a string:
string Document = File.ReadAllLines(File2);
System.Xml.Linq.XDocument.Parse(Document);
Or you can use XDocument.Load which expects a file path, not a string.
Related
I have created a program to read a file as array of bytes. The program is consuming word files by using docx library from Xceed. What I want to do is to recreate the parsed docx file from array of bytes.
To bytes:
var doc = Docx.Load("afile.docx");
...
return Encoding.Unicode.GetBytes(doc.Xml.Document.ToString());
Parse:
var doc = Docx.Create("anotherFile.docx");
var document = Encoding.Unicode.GetBytes({--returned bytes--}); <-- document is string with xml
How to save the document like the original?
I'm getting only blank file without any content.
using (var doc = DocX.Load("afile.docx"))
{
//here modify
doc.SaveAs("anotherFile.docx");
}
See this document BinaryWriter
bWriter.Writebytes(bytearray);
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("xyz.project.Folder1.Folder2.SomeFile.Txt"))
{
TextReader tr = new StreamReader(stream);
string fileContents = tr.ReadToEnd();
}
var html = File.ReadAllText(Properties.Resources.FilesTypes);
var html = File.ReadAllText(#"E:\New folder (44)\New Text Document.txt");
In the original and what is working i used the lastl ine:
var html = File.ReadAllText(#"E:\New folder (44)\New Text Document.txt");
But then i added the text file to my project resources since i want the file to be in the program all the time and not to read it from the hard disk.
Then i added the code with the assembly
Assembly.GetExecutingAssembly().GetManifestResourceStream("xyz.project.Folder1.Folder2.SomeFile.Txt"))
{
TextReader tr = new StreamReader(stream);
string fileContents = tr.ReadToEnd();
}
But in this case i need to type the name of the file manualy.
So i tried this line:
var html = File.ReadAllText(Properties.Resources.FilesTypes);
But getting exception:
Illegal characters in path
I want to save xml file, but I get error messages. Regarding the documentation
I should use a class in the Windows.Storage, but I don't know which class I should use and how to use it.
string filename;
XDocument doc = XDocument.Load(filename);
...
doc.Save(filename);
Error: Argument 1: cannot convert from 'string' to 'System.IO.Stream'
Error: The best overloaded method match for 'System.Xml.Linq.XDocument.Save(System.Xml.XmlWriter)' has some invalid arguments
StorageFile file = await StorageFile.GetFileFromPathAsync(filename);
using (Stream fileStream = await file.OpenStreamForWriteAsync())
{
doc.Save(fileStream);
}
how can i assign a to a variable, which is located at the same project, for example at my project i created a folder named App_Data and for example the file is file.dat , how can i assign the file at a variable,.. for example:
var file = App_Data/file.dat
I need it to be assigned to a variable because i will be using that variable as a parameter to a method,.. it used to be :
var file= HttpContext.Current.Request.MapPath("/App_Data/file.dat");
but now i want the path to be at the same project
if it should be absolute path it should be fine too
The MapPath should give you the absolute location of the file on disk from a relative url to the root of your website:
var absoluteFileLocation = HostingEnvironment.MapPath("~/App_Data/file.dat");
This should return something like:
c:\inetpub\wwwroot\MyWebSite\App_Data\file.dat
UPDATE:
It looks like you are trying to retrieve the contents of the file, not the location. Here's how this could be done:
var absoluteFileLocation = HostingEnvironment.MapPath("~/App_Data/file.dat");
string fileContents = System.IO.File.ReadAllText(absoluteFileLocation);
You need to read the file using one of the available methods (Streams, Readers, etc).
The easiest would be:
string fileContent = File.ReadAllText(fileNameAndPath);
where the variable fileNameAndPath contains the full path and file name to the file as described by Darin Dimitrov.
Your intention isn't exactly clear, anyway:
if you want file stats:
System.IO.File file = new System.IO.File("~/App_Data/file.dat");
if you want the file content use:
public static string readFileContent(String filename)
{
try
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(filename))
return sr.ReadToEnd();
}
catch { return String.Empty; }
}
I have problem with save xml in local folder.
I use their variable.
SelectFile is properites with name file ( for example goal.xml or goal(1).xml etc.)
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(SelectFile);
XDocument document = XDocument.Load(storageFile.Path);
XDocument document = XDocument.Load(storageFile.Path);
This document load good, but load document, not save.
var elementStepOne = document.Elements("StepOne").Single();
elementStepOne.Value = "delete content";
document.Save(SelectFile); // in line I try other mean write.
How I save this document? I want edit this document and save.
There are probably many ways to do this. One way is to use a file stream to save the xml:
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync(SelectFile);
XDocument document = XDocument.Load(storageFile.Path);
var elementStepOne = document.Elements("StepOne").Single();
elementStepOne.Value = "delete content";
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(
SelectFile,
CreationCollisionOption.ReplaceExisting);
using (var writeStream = await file.OpenStreamForWriteAsync())
{
document.Save(writeStream);
}