Let's say I have the following code:
StreamWriter sw = new StreamWriter(File.OpenWrite(Path));
sw.Write("Some stuff here");
sw.Dispose();
This code replaces the contents of the file with "Some stuff here," however I would like to add text to the file rather than replacing the text. How would I do this?
You could use the File.AppendAllText method and replace the 3 lines of code you have with:
File.AppendAllText(Path, "blah");
This way you don't have to worry about streams and disposing them (even in the event of an exception which by the way you are not doing properly) and the code is pretty simple and straightforward to the point.
You need to tell the StreamWriter you want to append:
var sw = new StreamWriter(path, true);
File.OpenWrite doesn't support appending.
Check out System.IO.File.AppendAllText
http://msdn.microsoft.com/en-us/library/ms143356.aspx
You can do what you want doing something like
File.AppendAllText(path, text);
There is a StreamWriter constructor which takes a bool as the 2nd parameter, which instructs the writer to append if true.
Use the append parameter:
StreamWriter sw = new StreamWriter(Path, true);
http://msdn.microsoft.com/en-us/library/36b035cb.aspx
To append text to a file, you can open it using FileMode.Append.
StreamWriter sw = new StreamWriter(File.Open(Path, System.IO.FileMode.Append));
This is just one way to do it. Although, if you don't explicitly need the StreamWriter object, I would recommend using what others have suggested: File.AppendAllText.
Related
if (string.IsNullOrEmpty(indata))
{
StreamWriter sw = new StreamWriter(#"c:\arjun.txt", true);
sw.WriteLine("0");
sw.Close();
}
This is my code. How can I overwrite a result in arjun.txt file I need single result.
The true part means "append" - either just get rid of it entirely, in which case you'll use the StreamWriter constructor overload which overwrites by defalut, or change true to false.
Or preferably, just use:
File.WriteAllLines(#"c:\argun.txt", new[] {"0"});
When you can specify all the data in one go, the convenience methods in File are really helpful.
I use this code to write a string to a file.
var fs = File.Open(path, FileMode.OpenOrCreate, FileAccess.Write);
var sw = new StreamWriter(fs, Encoding.UTF8);
sw.Write(dataString);
fs.Flush();
sw.Flush();
sw.Close();
When I debug it, I see the dataString correct. However, after writing to a file, there are some strings have wrong orders. Should I add a thread Sleep after writing data to the file because right after writing data to the file, I read it back for other process.
OR probably there is better way to write a string to a file?
Thanks in advance.
OR probably there is better way to write a string to a file?
Yes, there's a simpler way. Use File.WriteAllText or File.AppendAllText.
File.WriteAllText("output.txt", text, Encoding.UTF8);
Apart from being more concise, another advantage is that the file will be correctly closed even if there is an exception. However, I doubt that it will change the order in which the data is written to the file.
I need to create a large text document. I currently use StringBuilder to make the document and then call File.WriteallText(filename,sb.ToString). Unfortunately, this is now starting to throw out of memory exceptions.
Is there a better way to stream a StringBuilder to file or is there some other technique I should be using?
Instead of using StringBuilder, try using TextWriter (which has a broadly similar API, but which can write to a number of underlying destinations, including files) - i.e.
using(TextWriter writer = File.CreateText(path))
{
// loop etc
writer.Write(...);
}
More generally, it is worth separating the code that knows about files from the code that knows about how to write the data, i.e.
using(var writer = File.CreateText(path))
{
Serialize(writer);
}
...
void Serialize(TextWriter writer)
{
...
}
this makes it easier to write to different targets. For example, you can now do in-memory too:
var sw = new StringWriter();
Serialize(sw);
string text = sw.ToString();
The point being: your Serialize code didn't need to change to accomodate a different target. This could also be writing directly to a network, or writing through a compression/encryption stream. Very versatile.
Just use a StreamWriter that writes to a FileStream:
using (StreamWriter writer = new StreamWriter("filename.txt")) {
...
}
This will of course mean that you can't change the text that is already written, like you can do in a StringBuilder, but I assume that you are not using that anyway.
Why not streaming directly into the stream?
You could use the TextWriter.
You can use StreamWriter and write to the file directly.
I am saving data to a file every 60 secs, I have it saving every 60 secs ok but it deletes the previous data added. Is there a way in which it would add to the file rather than overwrite it. And without using save dialog as it is done in the background.
Any feedback is greatly appreciated
It seems opening the File in Append mode will solve your problem.
http://msdn.microsoft.com/en-us/library/3zc0w663.aspx
Try,
using (StreamWriter writer = new StreamWriter(#"C:\somefile.txt", true))
{
writer.WriteLine("Hello line..");
}
Specify FileMode.Append in the FileStream constructor.
Use File class AppendText method.
StreamWriter sw = File.AppendText("D:\\Text.txt");
sw.WriteLine("Hello");
sw.WriteLine("World");
sw.WriteLine("Test");
sw.Flush();
sw.Close();
You can use StreamWriter with append as true in the constructor.
See here.
OK as i am getting your question You are having a File And you want to save new data on that instead of replacing it
You can just open its content using stream reader.and append that data you want to insert on the file
using writer don't save file each time just append data on that file so when you just appending something on that it will not overwrite that file.
I have a simple question. I may be right but I want you people to ensure it since I am new at .NET.
StreamWriter SW = new StreamWriter(strFile);
SW.writeline("Hello");
SW.writeline("How are you?");
But in the middle, I don't want to save the data present in the SW variable, so what should I do? Should I use delete or detach?
Would reassigning memory to SW again cause any problems?
The StreamWriter class writes directly to the file.
Once you call WriteLine, it's too late to go back.
delete and detach do not undo changes. WriteLine writes directly to the file. You might be interested in using StringWriter for this purpose though.
StringWriter SW = new StringWriter();
SW.writeline("Hello");
SW.writeline("how r u");
if (commit == true)
File.WriteAllText (strFile, SW.ToString());
// else simply discard SW
Out of curiosity, why you would want to write something and then later discard it?