C#_WCF Xml Serialization - c#

I am serializing object through XMLSerializer ,but every time i invoke the method old data is getting replaced with the new data,i want to append the object every time i invoke not rewrite ,Below is the code which i have written please help me
XmlSerializer mySerializer = new XmlSerializer(typeof(Employee));
StreamWriter stream = new StreamWriter(#"C:\Users\divya.kakumanu\Documents\Visual Studio 2010\Projects\XmlFile.xml");
try
{
mySerializer.Serialize(stream, emp);
}
catch (SerializationException ex)
{
throw;
}
finally
{
stream.Close();
}

you can tell the StreamWriter to append to the file instead of overwriting it using this constructor:
new StreamWriter("your-file-path", **true**);
Also...Why are you rethrowing that exception? And you should really put a using block around the StreamWriter

Related

Having some trouble to delete a file using FileStreams in C#

I'm writing a program that uses text files in C#.
I use a parser class as an interface between the file structure and the program.
This class contains a StreamReader, a StreamWriter and a FileStream. I use the FileStream as a common stream for the reader and the writer, else these two will conflict when both of them have the file open.
The parser class has a class variable called m_path, this is the path to the file. I've checked it extensively, and the path is correct. OpenStreams() and and ResetStreams() work perfectly, however after calling CloseStreams() in the delete() function, the program goes to the catch clause, so File.Delete(m_path) won't get executed. In other situations the CloseStreams() function works perfectly. It goes wrong when I'm trying to close the StreamReader (m_writer), but it does give an exception (File is Already Closed).
/**
* Function to close the streams.
*/
private void closeStreams() {
if (m_streamOpen) {
m_fs.Close();
m_reader.Close();
m_writer.Close(); // Goes wrong
m_streamOpen = false;
}
}
/**
* Deletes the file.
*/
public int delete() {
try {
closeStreams(); // Catch after this
File.Delete(m_path);
return 0;
}
catch { return -1; }
}
I call the function like this:
parser.delete();
Could anybody give me some tips?
Your File.Delete(m_path); will never be called, because you get an exception here:
private void closeStreams() {
if (m_streamOpen) {
m_fs.Close();
m_reader.Close();
m_writer.Close(); // throws an exception here
m_streamOpen = false;
}
}
The exception is "Cannot access a closed file"
The cause is explained in the documentation of Close() in StreamReader:
Closes the System.IO.StreamReader object and the underlying stream, and releases any system resources associated with the reader.
There are also some articles about this behaviour:
Does disposing streamreader close the stream?
Is there any way to close a StreamWriter without closing its BaseStream?
Can you keep a StreamReader from disposing the underlying stream?
Avoiding dispose of underlying stream
You should consider re-writing your code and use using() statements.
However, I experimented a bit with your code, and it worked with calling Close() in other order:
m_writer.Close();
m_reader.Close();
m_fs.Close();
However, I assume that this works only by coincidence (I used .NET 4.0 and probably this will not work in another .NET version). I would strongly advice to not do it in this way.
I tested this:
using (FileStream fs = new FileStream(m_path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
using (StreamReader reader = new StreamReader(fs))
using (StreamWriter writer = new StreamWriter(fs))
{
// so some work here
}
File.Delete(m_path);
But, I know that this may not be for you, since you may want the read and write streams available as fields in your class.
At least, you have some samples to start with ...
File.Delete should work, either you didn't call your delete method, or m_path is an invalid path

System.IO.StreamWriter : Why do I have to use keyword "using"

//C#
using (System.IO.StreamWriter writer =
new System.IO.StreamWriter("me00.txt", true))
{
writer.WriteLine("Hey"); //saved
}
System.IO.StreamWriter writer02 = new System.IO.StreamWriter("me01.txt", true);
writer02.WriteLine("Now hey x2"); //not saved
File me00.txt and me01.txt are created, however only the first file's content gets saved.
me00.txt will have line hey. me01.txt will be an empty txt file; "Now hey x2" is not saved.
What does the keyword "using" do to cause this observation?
You don't have to use "using". It's just a shortcut to keep you from doing even more typing...
The alternative is to nest the whole thing in a try-finally construct like the following:
System.IO.StreamWriter writer = null;
try
{
writer = new System.IO.StreamWriter("me00.txt", true);
writer.WriteLine("Hey");
}
finally
{
if (writer != null)
writer.Dispose();
)
When the writer is disposed, it is also closed, which is the step you're missing. The using presents a tidy way to do all of this compactly.
Flush the Buffer. It works with the using statement, because the buffer is flushed when the stream being disposed/closed.
Just call writer02.Flush();
From the MSDN on StreamWriter.Flush :
Flushing the stream will not flush its underlying encoder unless you explicitly call Flush or Close
Also, you need to dispose the Stream. Don't forget to call the Dispose method when you are done with the stream.
The using statement will do it for you. If you call Dispose, you might not need to call Flush.
Add:
writer02.Close();
--------------:
public void Test()
{
//C#
using (System.IO.StreamWriter writer = new System.IO.StreamWriter("me00.txt", true))
{
writer.WriteLine("Hey");
}
}
Because this code is identical to the code
public void Test()
{
//C#
System.IO.StreamWriter writer = null;
try
{
writer = new System.IO.StreamWriter("me01111.txt", true);
writer.WriteLine("Hey"); //saved
}
finally
{
if (writer != null) //Flush data
{
((IDisposable)writer).Dispose();
}
}
}

System IO Exception : the process cannot access the file because it is being used by another process c#

I have seen several post for this problem .I have implemented all suggestion like using flush() , close() method on streamwriter and connection Object,use GC.Collect() to force cleanup,, use using{} to autodispose
I am Doing Simple Get Operation from DB and write to text file ..here is my Code
public void WriteToFile(string ProductName)
{
//Already Got Data from DB and stored in "ProductName"
//saving in File
if (!File.Exists(path11))
{
File.Create(path11);
StreamWriter tw = new StreamWriter(path11);
tw.WriteLine(ProductName+"#"+DateTime.Now.ToString());
tw.Flush();
tw.Close();
}
else if (File.Exists(path11))
{
StreamWriter tw = new StreamWriter(path11, true);
tw.WriteLine(ProductName + "#" + DateTime.Now.ToString());
tw.Flush();
tw.Close();
}
GC.Collect();
}
Another suggestion I Got is to lock the object ..But I cannot implement it ..
Any suggestion would be Helpful
File.Create creates the file and returns an open stream. You don't really need all that logic. Just use new StreamWriter(path11, true) which will create the file if it doesn't exist and append to it if it does. Also using is helpful:
public void WriteToFile(string ProductName)
{
//Get Data from DB and stored in "ProductName"
using (var tw = new StreamWriter(path11, true))
{
tw.WriteLine(ProductName+"#"+DateTime.Now.ToString());
}
}
FileCreate returns a stream which you should use to instantiate StreamWriter:
var file = File.Create(path11);
StreamWriter tw = new StreamWriter(file);
And you should use using blocks to make sure your stream and file is closed when you're finished writing.

Serialize and Deserialize Oracle.DataAccess.OracleException in C#

OracleException has no public constructors nor any way to get a new instance. I tried my XmlSerializerHelper class, but it requires a public parameterless constructor.
I used BinaryFormatter to serialize the OracleException and wrote it to a file.
How can I serialize OracleException in a file, and deserialize too using XmlSerializer -for testing reasons-?.
Reference:
http://geekswithblogs.net/WillSmith/archive/2008/07/25/testing-oracleexception.aspx
PD: Is better SoapFormatter or BinaryFormatter ?
Code
SerializationHelper.Serialize(#"C:\Temp\ExcepcionOracle.bin", ex);
var exOra = SerializationHelper.Deserialize(#"C:\Temp\ExcepcionOracle.bin");
public static void Serialize(string fileName, Object obj)
{
var binaryFormatter = new BinaryFormatter();
var fileStream = new FileStream(fileName, FileMode.Create);
try
{
binaryFormatter.Serialize(fileStream, obj);
}
catch (SerializationException ex)
{
throw new ApplicationException("The object graph could not be serialized", ex);
}
finally
{
fileStream.Close();
}
}
public static object Deserialize(string fileName)
{
var binaryFormatter = new BinaryFormatter();
var fileStream = new FileStream(fileName, FileMode.Open);
try
{
fileStream.Seek(0, SeekOrigin.Begin);
return binaryFormatter.Deserialize(fileStream);
}
catch (SerializationException ex)
{
throw new ApplicationException("Serialization Exception: " + ex.Message);
}
finally
{
fileStream.Close();
}
return null;
}
things like Exception simply aren't very suitable for xml serializers (and XmlSerializer in particular). In addition to the constructor issues (which some serializers can work around, and some can't), you are also likely to get issues with unexpected subclasses and arbitrary data in the collection.
If you are serializing as xml, you should probably just capture the key information you need - maybe the .Message and a few other things. Note also that in a client/server application the client doesn't really need to know much of the particulars of the failure - that should remain at the server. Either it is an exected error (invalid parameters, login issues, quota restrictions, etc), or it is an unexpected error. In the latter case: just say an unexpected error happened. The details would only be useful to a developer, and a developer should already have access to the server's error log.

Delete file using File.Delete and then using a Streamwriter to create the same file?

public void LoadRealmlist()
{
try
{
File.Delete(Properties.Settings.Default.WoWFolderLocation +
"Data/realmlist.wtf");
StreamWriter TheWriter =
new StreamWriter(Properties.Settings.Default.WoWFolderLocation +
"Data/realmlist.wtf");
TheWriter.WriteLine("this is my test string");
TheWriter.Close();
}
catch (Exception)
{
}
}
Will my method properly delete a file, then create one with "realmlist.wtf" as the name and then write a line to it?
I'm kind of confused because I can't see the line where it actually creates the file again. Or does the act of creating a StreamWriter automatically create a file?
The Stream Writer will create the file if it doesn't exist.
It will create it in the constructor, so when the StreamWriter is instantiated.
You know, if you pass a FileStream instance to the StreamWriter constructor, it can be set to simply overwrite the file. Just pass it along with the constructor.
http://msdn.microsoft.com/en-us/library/system.io.filestream.filestream.aspx
Example:
try
{
using (FileStream fs = new FileStream(filename, FileMode.Create))
{
//FileMode.Create will make sure that if the file allready exists,
//it is deleted and a new one create. If not, it is created normally.
using (StreamWriter sw = new StreamWriter(fs))
{
//whatever you wanna do.
}
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
Also, with this you won't need to use the .Close method. The using() function does that for you.
Try System.IO.File.CreateText.

Categories