c# streamwriter append text under each other - c#

I want to append lines to my file. I am using code:
StreamWriter sw = new StreamWriter("gamedata.txt", true);
sw.Write(the_final);
sw.Dispose();
at the moment it's outputting everything in a row.

Use sw.WriteLine(the_final); or sw.Write(the_final + "\n");
But much cleaner:
System.IO.File.AppendAllText("gamedata.txt", the_final + Environment.NewLine);

You should use writeline for writing in a new line sw.WriteLine(the_final)
It Writes a line terminator to the text stream
http://msdn.microsoft.com/en-us/library/ebb1kw70.aspx

You can use the WriteLine() method instead of Write().

I think the issue is when you're constructing your output into the variable: the_final
You need to insert new lines. You can do this by something along these lines:
the_final = "My First Line" + "\r\n";
the_final += "My Second Line!" + "\r\n";
thirdline = "My Third Line!";
the_final += thirdline + "\r\n";
The "\r\n" will produce the carriage return you're looking for.
The other suggestions everyone is making will only append 1 new line to the end of your output, leaving the rest on a single line still.

sw.Writeline(); writes a new line at the end.
sw.Write(); does not append a new line at the end.

Use sw.WriteLine() over Write()
MSDN:
Writes a line terminator to the text stream.
http://msdn.microsoft.com/en-us/library/system.io.streamwriter.writeline.aspx

Add a newline character manually
StreamWriter sw = new StreamWriter("gamedata.txt", true);
sw.Write(the_final + "\n");
sw.Dispose();
or use the writeline method
This question is easily answered by a short google search.It's good form to do a bit of research prior to posting

While everyone else has pretty much answered your initial question, may I also suggest this improvement?
using(StreamWriter sw = new StreamWriter("gamedata.txt", true))
{
sw.WriteLine(the_final);
}
When you have an object that inherits from IDisposable, it's good form to use using instead of disposing it manually. For one thing, using will dispose your object even if an exception is encountered.
Using documentation

Related

Unwanted second line in stream writer

I am coding a program, and i use stream writer, to write text to some files. The problem is, that when it writes to the text file, it leaves an unwanted extra line to the file, which confuses my program, when try to read it later. An example of the stream writer that i use is this:
string enbl = "Enabled = false;";
string path = Directory.GetCurrentDirectory();
System.IO.StreamWriter file = new System.IO.StreamWriter("path");
file.WriteLine(enbl);
file.Close();
Is it possible ti fix that ?
When you dont want that the output get an implicit CR+LF (0x0D + 0x0A) at the end you have to you use file.Write(enbl); instead of file.WriteLine(enbl);
Just use Write instead of WriteLine method.

Cut and paste line of text from text file c#

Hi everyone beginner here looking for some advice with a program I'm writing in C#. I need to be able to open a text document, read the first line of text (that is not blank), save this line of text to another text document and finally overwrite the read line with an empty line.
This is what I have so far, everything works fine until the last part where I need to write a blank line to the original text document, I just get a full blank document. Like I mentioned above I'm new to C# so I'm sure there is an easy solution to this but I can't figure it out, any help appreciated:
try
{
StreamReader sr = new StreamReader(#"C:\Users\Stephen\Desktop\Sample.txt");
line = sr.ReadLine();
while (line == "")
{
line = sr.ReadLine();
}
sr.Close();
string path = (#"C:\Users\Stephen\Desktop\new.txt");
if (!File.Exists(path))
{
File.Create(path).Dispose();
TextWriter tw = new StreamWriter(path);
tw.WriteLine(line);
tw.Close();
}
else if (File.Exists(path))
{
TextWriter tw = new StreamWriter(path, true);
tw.WriteLine(line);
tw.Close();
}
StreamWriter sw = new StreamWriter(#"C:\Users\Stephen\Desktop\Sample.txt");
int cnt1 = 0;
while (cnt1 < 1)
{
sw.WriteLine("");
cnt1 = 1;
}
sw.Close();
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
else
Console.WriteLine("Program Not Installed");
Console.ReadLine();
Unfortunately, you do have to go through the painstaking process of rewriting the file. In most cases, you could get away with loading it into memory and just doing something like:
string contents = File.ReadAllText(oldFile);
contents = contents.Replace("bad line!", "good line!");
File.WriteAllText(newFile, contents);
Remember that you'll have to deal with the idea of line breaks here, since string.Replace doesn't innately pay attention only to whole lines. But that's certainly doable. You could also use a regex with that approach. You can also use File.ReadAllLines(string) to read each line into an IEnumerable<string> and test each one while you write them back to the new file. It just depends on what exactly you want to do and how precise you want to be about it.
using (var writer = new StreamWriter(newFile))
{
foreach (var line in File.ReadAllLines(oldFile))
{
if (shouldInsert(line))
writer.WriteLine(line);
}
}
That, of course, depends on the predicate shouldInsert, but you can modify that as you see so fit. But the nature of IEnumerable<T> should make that relatively light on resources. You could also use a StreamReader for a bit lower-level of support.
using (var writer = new StreamWriter(newFile))
using (var reader = new StreamReader(oldFile))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (shouldInsert(line))
writer.WriteLine(line);
}
}
Recall, of course, that this could leave you with an extra, empty line at the end of the file. I'm too tired to say that with the certainty I should be able to, but I'm pretty sure that's the case. Just keep an eye out for that, if it really matters. Of course, it normally won't.
That all said, the best way to do it would be to have a bit of fun and do it without wasting the memory, by writing a function to read the FileStream in and write out the appropriate bytes to your new file. That's, of course, the most complicated and likely over-kill way, but it'd be a fun undertaking.
See: Append lines to a file using a StreamWriter
Add true to the StreamWriter constructor to set it to "Append" mode. Note that this adds a line at the bottom of the document, so you may have to fiddle a bit to insert or overwrite it at the top instead.
And see: Edit a specific Line of a Text File in C#
Apparently, it's not that easy to just insert or overwrite a single line and the usual method is just to copy all lines while replacing the one you want and writing every line back to the file.

c# File ReadAllText only reads first Char

in a current development I'm stuck with a strang problem.
In a bunch of written files on my harddisk i want to read out their content and write it into a textbox. It seams very easy, but somehow i stuck in a catch:
The files are containing something like this: "<LogItem><Row Number="0"><Column Name="object_id"><Old Value="2317"/><New Value="2317"/>"
I read them with:
textBox1.Text = File.ReadAllText(filetoread);
The result of this "ReadAllTest" is only the first Char "<" everything else in not written into the textbox.
Manually I can read the file with the normal Editor and this shows the complete text.
Are there any traps or limitations a haven't seen?
Best regards
It could be a problem of encoding... Rare but not impossible... Try, one at a time:
textBox1.Text = File.ReadAllText(filetoread, Encoding.Unicode);
textBox1.Text = File.ReadAllText(filetoread, Encoding.BigEndianUnicode);
textBox1.Text = File.ReadAllText(filetoread, Encoding.UTF32);
textBox1.Text = File.ReadAllText(filetoread, Encoding.UTF8);
textBox1.Text = File.ReadAllText(filetoread, Encoding.Default);
If the answer by xanatos doesn't work, try this:
using (StreamReader read = new StreamReader(filetoread))
{
textBox1.Text = read.ReadToEnd();
}
It doesn't use File.ReadAllText() as you can see.
And, this will work.

replacing \n with \r\n in a large text file

I have a large text file with a lot of \n that I need to replace with \r\n. With small text files, I was using the ReadToEnd method to get the file as a string and then use the Replace method and then write the string to a file. With a big file, however, I get an OutOfMemory exception because the string is too big. Any help would be greatly appreciated. Thanks.
private void foo() {
StreamReader reader = new StreamReader(#"D:\InputFile.txt");
StreamWriter writer = new StreamWriter(#"D:\OutputFile.txt");
string currentLine;
while (!reader.EndOfStream) {
currentLine = reader.ReadLine();
writer.Write(currentLine + "\r\n");
}
reader.Close();
writer.Close();
}
This should resolve your problem. Please note, that reader.ReadLine() cuts of the trailing "\n".
DiableNoir's solution is the right idea, but the implementation is buggy and it needs some explanation. Here's an improved one:
using (var reader = new StreamReader(#"D:\InputFile.txt"))
using (var writer = new StreamWriter(#"D:\OutputFile.txt")) // or any other TextWriter
{
while (!reader.EndOfStream) {
var currentLine = reader.ReadLine();
writer.Write(currentLine + "\r\n");
}
}
You use a TextReader for input and a TextWriter for output (this one might direct to a file or to an in-memory string). reader.ReadLine will not return the line ending as part of the line, so you need to write it explicitly (instead of using string.Replace, which will not accomplish anything at all).
Also, exactly because you will never see \n or \r as part of currentLine, this program is safe to run again on the output it has produced (in this case its output will be exactly identical to its input). This would not be the case if currentLine included the line ending, because it would change \n to \r\n the first time, and then make it \r\r\n the second time, etc.
You could use Read and specify how many bytes to read each time. Such as read the file in 10 MB chunks.
Or if you need like a larger buffer you can use StreamReader.ReadBlock();

c# saving textbox.text to txt file. txt file doesn't recognize end of line character

I have the following code:
void AppendText(string txt)
{
txt = txt + "\r\n";
Textbox1.AppendText(txt);
Textbox1.Select(Textbox1.Text.Length,0);
}
//....
void someFunction()
{
//...
string log = #"C:\log.txt";
using (FileStream fs = new FileStream(log, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.Write(Textbox1.Text);
}
}
//...
}
The problem is in Textbox1.Text field in the form, "\r\n" works fine, but when I copy the Textbox1.Text to log.txt, the log.txt doesn't have new line where it's supposed to be. Instead there's a strange charater like this "[]" where "\r\n" is. I think problem lies in the sw.Write(tbox.text) right? But I don't know how to fix it. Could anyone give me a hand? Help is really appreciated. Thanks in advance.
My guess would be that the Textbox creates unicode characters (two bytes per character).
In what format are you reading the data? ASCII unicode UTF?
If I remember correctly /n/r is an old trick to write a newline character to the string but in what format and what does it mean? Environment.Newline is much better and would work on windows mobile/unix builds too.
I usually create a class level variable called br with environment.newline as its content, creates much shorter code.
You should do like this.
string log = #"C:\log.txt";
using (FileStream fs = new FileStream(log, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(fs))
{
foreach(string line in Textbox1.Lines)
sw.Write(line+sw.NewLine);
}
}
Your code is correct. Just add sw.Close(); after sw.Write(Textbox1.Text);

Categories

Resources