It has yes guy, but before you should consider the possibility that the file is coming corrupted or something like that. If you are sure that this file is intact, and that there is only one invalid character at the end for some unknown reason (?), you can play the file in memory except the last character, getting its valid xml.
There are two ways I know how to do this. Note the following code:
METHOD 1
using (MemoryStream ms = new MemoryStream()) // cria um stream de memória
using (var fs = new FileStream(@"C:\sample.xml", FileMode.Open, FileAccess.Read))
// abre o arquivo xml. No caso C:\sample.xml
{
byte[] bytes = new byte[fs.Length]; // onde ficará o conteúdo do arquivo - 1
fs.Read(bytes, 0, (int)fs.Length); // lê o arquivo
ms.Write(bytes, 0, (int)fs.Length-1); // escreve tudo exceto o último byte (length - 1)
ms.Seek(0, SeekOrigin.Begin); // volta para o início do stream
XDocument doc = XDocument.Load(ms); // carrega o arquivo em memória
Console.WriteLine(doc.Root.Value); // teste de leitura
}
METHOD 2
using (var fs = new FileStream(@"C:\sample.xml", FileMode.Open, FileAccess.Read))
// cria um arquivo mapeado em memória a partir do seu FileStream
using (var mmf = MemoryMappedFile.CreateFromFile(fs,"xml",fs.Length,MemoryMappedFileAccess.Read,null,System.IO.HandleInheritability.None,true))
{
// cria um stream que enxerga até o final do arquivo - 1
using (var str = mmf.CreateViewStream(0, fs.Length - 1, MemoryMappedFileAccess.Read))
{
XDocument doc = XDocument.Load(str); // lê a partir do stream
Console.WriteLine(doc.Root.Value);
}
}
The second uses Memory-Mapped Files.
One detail is that these methods copy the contents of the file to memory, it is not the most performative thing in the world so take care when doing this with a large XML, and never forget the using
to "discard" your Stream
after use.
Good luck and I hope I helped.
You could edit the file with
StreamWriter
and remove this character before opening as aXmlDocument
– iuristona