How would I replace the text in a file with c#. I can write to the file, but if I write to the file a second time it appends the new data to the old rather than replace it. Here is a copy of what I'm using

fsFile = new FileStream("test.txt",FileMode.Open);
StreamWriter swOut = new StreamWriter(fsFile);

The output looks like this:

And I want it to look like this:
Any suggestions?

Recommended Answers

All 4 Replies


I'm not C expert but you need to open file as New (C may call it something else, but principle is correct), not Open.


Denis is correct. Use FileMode.Create.
With this mode, if the file doesn't exist it is created, or else overwritten (I believe this is what you want).

Yes that is was I was looking for. Thank you guys!!

Thanks for helping Scru - glad to hear it is working Atrus. Thanks for letting us know.


Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.