Xml editing problem using C# - c#

I have posted a question previous regarding editing my xml document via c#
C# write to XML error
However im now having trouble with it again. Im using the exact code that worked then but getting problems again!
When I first click the button it seems to work however when I click it again I get the error
Data at the root level is invalid. Line 83, position 10
When you then open the XML document for some reason the characters "" get added to the start of the xml document so I get
"<?xml version="1.0" encoding="UTF-8"?>"
I dont understand why and its really driving me insane. I'm sure it was working before.
My code:
path = test.xml
using (FileStream READER = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
System.Xml.XmlDocument Temp = new System.Xml.XmlDocument();
Temp.Load(READER);
using (FileStream WRITER = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
Temp.Save(WRITER);
}
}

UPDATE #2:
I compiled your sample as is and it worked perfectly for me. I tested it with a file created straight from code and also with a xaml file created in Visual Studio. So it seems the file you're working with is corrupted or have an encoding problem.
As far as I know you can't do anything about corrupted file, but as for encoding you can specify it when reading by using a StreamReader object. You just pass a desired encoding and your reader stream to StreamReader's constructor. Also it has an option to detect the encoding from byte order marks.
using (TextReader txtreader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), Encoding.GetEncoding(1251 /*desired codepage here*/)))
{
document.Load(txtreader);
}
or
using (TextReader txtreader = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite), true /*tries to detect the encoding*/))
{
document.Load(txtreader);
}
Of course, you should save the file using the same encoding or you'll have problems next time you run your loading code.
Also I'm attaching a code which creates a file if it doesn't exist or just modifies it if it already exists.
class Program
{
static readonly string path = #"C:\Users\Dmitry\Documents\test_3.xml";
static void Main(string[] args)
{
for (int i = 0; i < 10; i++)
test(path);
}
static void test(string path)
{
XmlDocument document = new XmlDocument();
if (File.Exists(path))
{
using (Stream readStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
document.Load(readStream);
}
}
else
{
document.AppendChild(document.CreateXmlDeclaration("1.0", "UTF-8", String.Empty));
document.AppendChild(document.CreateElement("Test"));
}
document.DocumentElement.AppendChild(document.CreateElement("Node"));
using (FileStream WRITER = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
document.Save(WRITER);
}
}
}
I hope it helps you.

Related

NPOI 2.6.0-rc-3 with .net framework 4.8.1 for updating .xlsx - losses charts in excel file

I use NPOI 2.6.0-rc-3 with .net framework 4.8.1 for updating .xlsx file. Excel file includes charts with it. excel file get crashed and after saving. After recovering the same file it losses charts in excel.
Used the following code.
XSSFWorkbook wb1 = null;
using (var file = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
{
wb1 = new XSSFWorkbook(file);
file.Close();
//Updated the cell values here
using (var file2 = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
{
wb1.Write(file2);
file2.Close();
}
}
Please help regrading this matter
Try to modify the cells out of the using block (you dont need to keep the file open to modify the IWorkbook) and then save it using a diferent stream:
IWorkbook wb1 = null;
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
wb1 = new XSSFWorkbook(file);
}
//Updated the cell values here
using (FileStream fileWrite = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
wb1.Write(fileWrite);
}

Modify a file content in C# using the Stream's API

I have a .json file who handles the user's roles and I have wrote a Repository who's responsible of adding/removing roles to users. The pb is that when I modify the file I want to be sure that no one access it except me.
Here's (roughly) the code I use:
using (var fileStream = new FileStream(_rolesFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
using (var streamReader = new StreamReader(fileStream))
using (var streamWriter = new StreamWriter(fileStream))
{
var oldContent = streamReader.ReadToEnd();
var contentObject = Deserialize(oldContent);
Modify(contentObject)
var newContent = Serialize(contentObject);
fileStream.Seek(0, SeekOrigin.Begin);
streamWriter.Write(newContent);
}
The pb with this solution is that if newContent is a string shorter that oldContent some characters will be remaining in the file.
A solution I found is to add the following code:
using (var fileStream = new FileStream(_rolesFilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
using (var streamReader = new StreamReader(fileStream))
using (var streamWriter = new StreamWriter(fileStream))
{
//...
var newContent = Serialize(contentObject);
var endPosition = fileStream.Position;
fileStream.Seek(0, SeekOrigin.Begin);
streamWriter.Write(newContent);
streamWriter.Flush();
while (fileStream.Position < endPosition)
{
streamWriter.WriteLine();
streamWriter.Flush();
}
}
It works well but does not look very clean to me. Are there any better solution who ensure that I keep the control of the file ?
Thanks in advance,
Thomas
You can do fileStream.SetLength(fileStream.Position) to truncate the remaining part of the file. This assumes that the FileStream is left correctly positioned by the StreamWriter after use, but that's an assumption your current code seems to be making too.
(This is a safer assumption than the corresponding usage of StreamReader where internal buffering may mean that the underlying stream's position is further advanced than the latest data returned by a call to a Read method)

Read file that's already used by another process

I have a C# app that tries to read a log file which is being written to by another app. When I try to read the file, I get IOException
"The process cannot access the file ... because it is being used by
another process."
What I tried using so far are the following, but none of them fix the problem
var log = File.ReadAllText(logPath);
var stream = new FileStream(logPath, FileMode.Open);
using (var stream = File.Open(logPath, FileMode.Open))
{
}
try this:
FileStream logFileStream = new FileStream("c:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader logFileReader = new StreamReader(logFileStream);
while (!logFileReader.EndOfStream)
{
string line = logFileReader.ReadLine();
// Your code here
}
// Clean up
logFileReader.Close();
logFileStream.Close();
edited with MethodMan's suggestions
using(FileStream logFileStream = new FileStream(#"c:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using(StreamReader logFileReader = new StreamReader(logFileStream))
{
string text = logFileReader.ReadToEnd();
// Your code..
}
}
You can do nothing, if the "another app" does not use Share.Read while creating/opening the file.

IsolatedStorage in Window Phone 7.5

I am working with IsolatedStorage in Windows Phone 7.5. I am trying to read some text from a file. But the debugger says the operation is not permitted on IsolatedStorageFileStream. Why?
//Read the file from the specified location.
fileReader = new StreamReader(new IsolatedStorageFileStream("info.dat", FileMode.Open, fileStorage));
//Read the contents of the file (the only line we created).
string textFile = fileReader.ReadLine();
//Write the contents of the file to the MEssageBlock on the page.
MessageBox.Show(textFile);
fileReader.Close();
UPD my new code
object _syncObject = new object();
lock (_syncObject)
{
using (var fileStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (FileStream stream = new FileStream("/info.dat", FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var reader = new StreamReader(stream))
{
string textFile = reader.ReadLine();
MessageBox.Show(textFile);
}
}
}
}
}
Try this, it works for me: Hope it works for you too
String sb;
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(fileName))
{
StreamReader reader = new StreamReader(new IsolatedStorageFileStream(fileName, FileMode.Open, myIsolatedStorage));
sb = reader.ReadToEnd();
reader.Close();
}
if(!String.IsNullOrEmpty(sb))
{
MessageBox.Show(sb);
}
}
If this doesn't work, then maybe your file doesn't exist.
Normally when I've used isolated storage, I've done something like:
using (var stream = fileStorage.OpenFile("info.dat", FileMode.Open))
{
using (var reader = new StreamReader(stream))
{
...
}
}
... rather than calling the constructor directly on IsolatedStorageFileStream. I can't say for sure whether that'll sort it out, but it's worth a try...
Just a guess:
WP emulator will reset all Isolatd Storage contents when it's closed
if you used FileMode.Open with a path to a non existing file you'll get Operation not permited exception.
You can use fileStorage.FileExists() to check if the file is there or use FileMode.OpenOrCreate.

Populating xml using c# error

I am populating an xml document using c#. If I populate it once then everything is ok but when I try to repopulate it a second time (without closing the program) I get an error message and rubish gets written to the bottom of the xml file.
I'm sure I've found the answer to this question before but I can't find it.
I'm sure its something to do with the fact that I'm not closing something down after updating the xml document or something but I can't remember what exactly I have to close down.
Sorry I hope you all understand. I find it difficult to explain.
Code:
using (FileStream READER = new FileStream(fpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
System.Xml.XmlDocument Template = new System.Xml.XmlDocument();// Set up the XmlDocument //
Template.Load(READER); //Load the data from the file into the XmlDocument //
//**********Grab nodes to be written to********
using (FileStream WRITER = new FileStream(fpath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
//Set up the filestream (READER) //
//Write the data to the filestream
Template.Save(WRITER);
You read and write in the same file fpath
You have to close the reader after Template.Load(READER);
using (FileStream READER = new FileStream(fpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
System.Xml.XmlDocument Template = new System.Xml.XmlDocument();// Set up the XmlDocument //
Template.Load(READER); //Load the data from the file into the XmlDocument //
}
//**********Grab nodes to be written to********
using (FileStream WRITER = new FileStream(fpath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite))
{
//Set up the filestream (READER) //
//Write the data to the filestream
Template.Save(WRITER);
...
}

Categories