Main Site Documentation

FileStream Position throw Exception


#1

When I’m trying to set position of filestream it throws An unhandled exception of type ‘System.IO.IOException’ occurred in System.IO.dll


string filenamepath = @ "\SD\" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xml";
fs = new FileStream(filenamepath, FileMode.Append, FileAccess.Write);
fs.Position = 200;
XmlWriter xmlFileWriter = System.Ext.Xml.XmlWriter.Create(fs);
xmlFileWriter.WriteStartElement("event");

Did someone had such a problem with filestream? Don’t know if it’s MF issue or EMX SD card handling thing?
BTW: fs.Position property has value 261 when it’s throw an error so setting it to 200 shouldn’t be any problem I suppose.


#2

Try this instead:


fs = new FileStream(filenamepath, FileMode.Open, FileAccess.Write);
fs.Seek(200, SeekOrigin.Current);

I believe this code should put you at byte 200 like you expect. Notice the File.Open instead of File.Append in the constructor.

Since you’re setting the second parameter in the FileStream constructor to FileMode.Append, it’s starting your stream at the end of the file (that’s why your FileStream.Position property reads 261). Setting the Position property directly might not allow you go “backwards” in the stream - maybe that’s why you get the exception. Anyway, try the above snippet and see if it works.


#3

Your code is working, but I think that access mode is something that block this whole process.


fs = new FileStream(filenamepath, FileMode.Open, FileAccess.ReadWrite);
fs.Position = fs.Length - 9;
// Back in file to avoid overwriting "</events>"
XmlWriter xmlFileWriter = System.Ext.Xml.XmlWriter.Create(fs);

Now this xmlWriter is working properly so I have always properly formatted XML file with all tags closed every time I’m writing something new to file.

Thanks Chuckie.


#4

Hi i work on fez panda ii, and i couldn’t append data to xml file. i need help. if you have sample code, please share me. i am stucked :frowning:

judasis


#5

Where did you stuck? Show some code.


#6

i solved my problem. i replace FileMode.Open from FileMode.Append. it was easy, but i couldn’t have seen. Thanks for your interest Architech…
Judasis


#7

You are welcome! Good luck with the project.