I have a console application which writes details of the processed jobs into .txt file. I use this code to do it:
StreamWriter jp = new StreamWriter(jobsProcessed);
jp.WriteLine(DateTime.Now.ToString());
jp.WriteLine(info);
jp.WriteLine("------");
jp.Close();
Unfortunately every time a job is being processed new "info" string replaces the previous one. Is there any method to add new text to the end or beginning of the text file?
You can use StreamWriter Constructor (String, Boolean), where second boolean parameter indicates either the data has to be appended to the already available one or not.
And also avoid calling Close and use using statement
using(StreamWriter jp = new StreamWriter(jobsProcessed))
{
jp.WriteLine(DateTime.Now.ToString());
jp.WriteLine(info);
jp.WriteLine("------");
//jp.Close(); //NO NEED MORE
}
The good about this that even if exception occures, which can happen, the stream will be Disposed, by the way.
There is an overload to the StreamWriter constructor which takes a second parameter called append;
using (StreamWriter jp = new StreamWriter(jobsProcessed, true))
{
jp.WriteLine(DateTime.Now.ToString());
jp.WriteLine(info);
jp.WriteLine("------");
}
It's also better practice to wrap your StreamWriter up in a using block like above.
StreamWriter jp = new StreamWriter(jobsProcessed,true);
Second parameter
//Determines whether data is to be appended to the file. If the file exists
//and append is false, the file is overwritten. If the file exists and append
// is true, the data is appended to the file. Otherwise, a new file is created.
http://www.dotnetperls.com/streamwriter
http://social.msdn.microsoft.com/Forums/zh/clr/thread/17cd8ccf-7e53-41de-b4cc-221da70405a4
Just amend this:
StreamWriter jp = new StreamWriter(jobsProcessed);
To this:
StreamWriter jp = new StreamWriter(jobsProcessed, true);
// using (StreamWriter jp = new StreamWriter(jobsProcessed)) Overwrites, not good for you!
using (StreamWriter jp = new StreamWriter(jobsProcessed, true)) // Appends, good for you!
{
jp.WriteLine(DateTime.Now.ToString());
jp.WriteLine(info);
jp.WriteLine("------");
}
But you could semplify your code like so:
String[] content = File.ReadAllLines(jobsProcessed);
String[] newContent = new String[3];
newContent[0] = DateTime.Now.ToString();
newContent[1] = info;
newContent[2] = "------";
File.AppendAllLines(jobsProcessed, newContent);
Related
So I File.Create a txt and then try to write a line on it like so:
StreamWriter.WriteLine("string");
but it just skips right past it like the line doesn't exist without any messages, warnings, or errors.
This is how to use streamwriter.
using (StreamWriter writetext = new StreamWriter("C:\\sample.txt", false))
{
writetext.WriteLine("Header");
}
using (StreamWriter writetext = new StreamWriter("C:\\sample.txt", true))
{
foreach (var data in _data)
{
writetext.WriteLine("Sample");
}
}
Notice the boolean (true or false) in the second parameter of StreamWriter class
new StreamWriter("C:\\sample.txt", true)
True: Append in file if exists
False: Overwrite file if exists
this is a bit of a long answer and example. But when I am writing commands to my digital assistant this is how I use StreamWriter.
StreamWriter sw;
StreamReader sr;
then in the code you do this
Settings.Default.ShellC = #"C:\Users\" + userName + "\\Documents\\Alexis Custom Commands\\Shell Commands.txt";
scpath = Settings.Default.ShellC;
if (!File.Exists(scpath))
{ sw = File.CreateText(scpath); sw.Write("My Documents"); sw.Close(); }
the textbox is the ShellC design name. you would add that to your properties then, in your using statements add the properties. then if you wanted to read them back then you would use
StreamReader
and then ference the file as
ArrayShellCommands = File.ReadAllLines(scpath);
How can I create and then modify writing on this file?
string fileName = #"C:\...\MioFile.txt";
In main:
File.CreateText(fileName);
Then when I would edit the file by adding text.
StreamWriter writer = new StreamWriter(fileName);
sw.WriteLine("Hello"+variable);
sw.Close();
But the file is empty and I cannot write anything.
I would like create a file.txt and I would like for this file to always add new information every time I call it in writing mode. A kind of "log file".
Use File.AppendAllText instead of StreamWriter. Its simple:
File.AppendAllText(filename, "Hello"+variable);
You have sw.WriteLine, But your streamwriter is called "writer". That might be the problem.
I like to use the "using" statements:
//full path
var fileName = #"C:\Users\...\Desktop\newFile2.txt";
//Get the stream in FileMode.Append (will create or open)
using (var fileStream = new FileStream(fileName,FileMode.Append))
{
//pass the fileStream into the writer.
using (var writer = new StreamWriter(fileStream))
{
writer.WriteLine("{0} => file appended", DateTime.Now);
}//dispose writer
}//dispose fileStream
I was doing some trials on the basis of the following Q&A: Where does Console.WriteLine go in ASP.NET?.
The code I tried goes like below:
var fs = new System.IO.FileStream(#"D:\log.txt", System.IO.FileMode.Append);
var tr = new System.IO.StreamWriter(fs);
Console.SetOut(tr);
Console.WriteLine("My Default Debugging");
fs.Close();
Here I am setting the FileStream fs to StreamWriter tr and in turn setting it as Console.Out by calling Console.SetOut(). So, by that I am expecting it to write to the file by Console.WriteLine(). Though my file gets created, it is empty.
What can be the thing I am missing here?
try tr.WriteLine("string"); instead.
var fs = new System.IO.FileStream(#"D:\log.txt", System.IO.FileMode.Append);
var tr = new System.IO.StreamWriter(fs);
Console.SetOut(tr);
Console.WriteLine("My Default Debugging");
tr.Close();
fs.Close();
Maybe it's because you didn't close the StreamWriter before you closed the FileStream?
Becuase Console.WriteLine() doesn't do that?
Writes the specified data, followed by the current line terminator,
to the standard output stream.
I am trying to save a file using DialogResult and StringBuilder. After making the text, I am calling the following code to save the file:
if (dr == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(saveFileDialog1.FileName);
sw.Write(sb.ToString());
sw.Close();
}
I tried to add the second parameter to StreamWriter as Encoding.UTF8 but since the first argument is a string rather than a Stream, it does not compile it.
How can I convert that string to a stream to be able to pass the second parameter as Encoding?
The reason for this, is that somewhere in my text I have µ but when the file is saved it shows like μ so the µ is getting screwd!
Thanks
Just wrap it in a FileStream.
StreamWriter sw = new StreamWriter(
new FileStream(saveFileDialog1.FileName, FileMode.Open, FileAccess.ReadWrite),
Encoding.UTF8
);
If you want to append, use FileMode.Append instead.
You should also call Dispose() on a try/finally block, or use a using block to dispose the object when it exceeds the using scope:
using(
var sw = new StreamWriter(
new FileStream(saveFileDialog1.FileName, FileMode.Open, FileAccess.ReadWrite),
Encoding.UTF8
)
)
{
sw.Write(sb.ToString());
}
This will properly close and dispose the streams across all exception paths.
UPDATE:
As per JinThakur's comment below, there is a constructor overload for StreamWriter that lets you do this directly:
var sw = new StreamWriter(saveFileDialog1.FileName, false, Encoding.UTF8);
The second parameter specifies whether the StreamWriter should append to the file if it exists, rather than truncating it.
There is a constructor for filename, appendMode, encoding.
With a proper using block it looks like:
if (dr == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(saveFileDialog1.FileName,
false, Encoding.UTF8))
{
sw.Write(sb.ToString());
//sw.Close();
}
}
There is a StreamWriter(string path, bool append, Encoding encoding) constructor - you could just explicitly specify the append flag too?
I said you ought to wrap your StreamWriter in a using too, i.e.
if (dr == DialogResult.OK)
{
using(StreamWriter sw = new StreamWriter(saveFileDialog1.FileName, false, Encoding.UTF8)) {
sw.Write(sb.ToString());
sw.Close();
}
}
although realistically this won't make any difference here. This effectively puts a try/finally around the code so that the StreamWriter will get cleaned up (it'll call sw.Dispose() even if an exception gets thrown in the meantime. (Some people will say this also means you no longer need the .Close since the Dispose will take care of that too but I prefer to have it anyway.)
setting UTF8 encoding working with Arabic font is the best thing I did:
using (var sw = new StreamWriter(
new FileStream(temporaryFilePath,
FileMode.Create,
FileAccess.ReadWrite),
Encoding.UTF8))
{
sw.Write(sb.ToString());
}
)
The easiest way is to use the right constructor.
StreamWriter(String, Boolean, Encoding)
Initializes a new instance of the StreamWriter class for the specified file by using the specified encoding and default buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.
C#
public StreamWriter (string path, bool append, System.Text.Encoding encoding);
My code is
System.IO.StreamWriter objStreamWriter = new System.IO.StreamWriter(File);
objStreamWriter.Write(txtEditor.Text);
objStreamWriter.Close();
txtEditor.Text = string.Empty;
I got a message The file has been modified out side of............. but my text file is empty. When in debug mode, I got a value of textEditor and path is not a problem. Am I missing some stupid things.
Thanks.
You have to verify the content of txtEditor before you write it to disk file.
string text=txtEditor.Text;
if(text.Trim.Length!=0)
{
using(System.IO.StreamWriter objStreamWriter = new System.IO.StreamWriter(File))
{
objStreamWriter.Write(text);
}
}
Use the StreamWriter by the "using" keyword for correct writing in to textfile.
using (StreamWriter writer = new StreamWriter("important.txt"))
{
writer.Write("Word ");
writer.WriteLine("word 2");
writer.WriteLine("Line");
}
Refer to the C# Using StreamWriter for more info