/r after every word - c#

So, I am creaing a "Hangman" game, with a word editor to put your own word in the game. I have a form which opens a text file and displays the content in a multi-line textbox. After that the user can edit the textbox. If you press "save" the content from the textbox will be saved to the text file.
Now, everything works good, the reading and the writing. But now if I want to play my words, its always longer than the word I entered. I found out via debugging that somehow my programm adds "/r" behind every word. For example if I enter "Test" in the wordeditor, the game would use it as "Test/r".
I believe it is an error in the wordeditor so here is the code:
namespace Hangman
{
public partial class WordEditor : Form
{
public WordEditor()
{
InitializeComponent();
using (StreamReader sr = new StreamReader(new FileStream("C:\\Users\\tstadler\\Desktop\\Hangman.txt", FileMode.Open)))
{
string[] Lines = sr.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < Lines.Length; i++)
{
textBox1.Text += Lines[i] + Environment.NewLine;
}
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
string[] words = textBox1.Text.Split('\n');
FileStream overwrite = new FileStream("C:\\Users\\tstadler\\Desktop\\Hangman.txt", FileMode.Create);
using (StreamWriter file = new StreamWriter(overwrite))
{
for (int i = 0; i < words.Length; i++)
{
file.Write(words[i] + Environment.NewLine);
}
}
MessageBox.Show("Words saved. ");
}
Can anyone tell me if he recognizes the error?
Thanks.

Everywhere you insert new lines you use Environment.NewLine - except for one line:
string[] words = textBox1.Text.Split('\n');
Which results in a string splitted by \n whereas Environment.NewLine consists of \r\n on a Windows system. Thus after the split the \rremains at the end of the string.
To resolve that issue simple replace the line mentioned above with
string[] words = textBox1.Text.Split(new string[] { Environment.NewLine });

Use File.ReadAllLines:
Opens a text file, reads all lines of the file, and then closes the file:
A line is defined as a sequence of characters followed by a carriage return \r, a line feed \n, or a carriage return immediately followed by a line feed.
and File.WriteAllLines:
Creates a new file, write the specified string array to the file, and then closes the file.
sample:
string[] lines = File.ReadAllLines("filePath");
File.WriteAllLines("filePath", textBox.Text.Split(new[] {Environment.NewLine}));

Your solution is almosut correct but very verbose look at this:
File.ReadAllLines;
and
File.WriteAllText;
so your read section would be:
textBox1.Text = string.Join(Environment.NewLine,
File.ReadAllLines(filePath).Where(x=>!string.IsNullOrWhiteSpace(x)));
and write
File.WriteAllText(filePath,textBox1.Text);

Related

C# replace {CRLF} with {LF}

I have a text file sent from others. If I open in NotePad++ and view all the symbols, I can see both {LF} and {CRLF} work as line separator.
Example:
line1: ABC {CRLF}
line2: XYZ {LF}
Question: If I want to replace {CRLF} with {LF} and write to a new file, why the output text file cannot show separate line and the separator symbols disappear. Write just writes the line and append another line without start a new line, but the line still has {LF} in it, hasn't it? Is that because I am working in Windows system? But how the original file with both {LF} and {CR}{LF} can be viewed as two separate lines?
Code is very simple:
using (StreamReader sr = new StreamReader(#"\\...\TEST.txt"))
{
using (StreamWriter sw = new StreamWriter(#"\\...\TEST2.txt"))
{
string line = "";
while ((line = sr.ReadLine()) != null)
{
sw.Write(line.Replace("\r\n", "\n"));
}
}
}
When you use ReadLine() you're trimming the EOL characters (CR and LF). Instead you should do one of the following ways:
string file1 = #"\\...\TEST.txt";
string file2 = #"\\...\TEST2.txt";
using (StreamReader sr = new StreamReader(file1))
{
using (StreamWriter sw = new StreamWriter(file2))
{
string text = sr.ReadToEnd();
sw.Write(text.Replace("\r\n", "\n"));
}
}
Or
File.WriteAllText(file2,File.ReadAllText(file1).Replace("\r\n", "\n"));
But only if your file is not too big. Otherwise, Jim solution is the way to go.
Your code doesn't work because when you call sr.Readline(), the returned string does not contain the CRLF characters. Those characters are added by WriteLine, which is essentially Write(s + Environment.NewLine).
To make your code work, change it to
while ((line = sr.ReadLine()) != null)
{
sw.Write(line + "\n");
}
You can simplify your code with:
File.WriteAllLines("outputFileName",
FileReadLines("inputFileName").Select(s => s + "\n");

Append to the second to last line in a text file

So I'm making a program to type what's in my clipboard into a text file, I plan on later transporting this information into an AHK script, but I want to do this all in one program, so if possible it will append to the .ahk file, but instead of it appending to the very last line, I need it to append to the line before return, which is the final line of the file.
Send ::redeem N4E2vzCEp {enter}
Sleep 1000
return
That's the end of the file, if possible I want my program to do something like:
string pasted = Clipboard.GetText();
sw.WriteLine.SecondLastLine("Send ::redeem " + pasted + " {enter}");
sw.WriteLine.SecondLastLine("Sleep 1000"); //Fully aware that secondlastline is not a valid command
But I don't know what the proper way of actually coding this would be.
Current code:
private void paste_Click(object sender, EventArgs e)
{
string path = #"c:\users\john\desktop\auths.txt";
using (StreamWriter sw = File.AppendText(path))
{
string pasted = Clipboard.GetText();
sw.WriteLine("Send ::redeem " + pasted + " {enter}");
sw.WriteLine("Sleep 1000");
}
}
What you can do is reading all lines into a List and then insert the new line at a specific position and write the lines back to the file.
List<string> lines = File.ReadAllLines("your file").ToList();
lines.Insert(lines.Count - 2, "new line");
File.WriteAllLines("your file", lines);

How to save text to file with the separated lines in Unity with c#

When I try to save some text in Editor, I got result1 when I want to save some text in the separated lines in my Android device, but I have result like this result2
result 1 is
a
b
c
d
result 2 is
abcd
here's my code
public void savetofile()
{
StreamWriter SW = new StreamWriter(" path to file ");
SW.WriteLine("a");
SW.WriteLine("b");
SW.WriteLine("c");
SW.WriteLine("d");
}
According to docs of WriteLine
Writes a string followed by a line terminator to the text string or stream.
each line should be printed with a newline at the end, but as showed in example this doesn't happen. Can somebody tell me what's going wrong?
You can use the control code "\n" for a new line.
public void savetofile()
{
StreamWriter SW = new StreamWriter(" path to file ");
SW.WriteLine("a");
SW.WriteLine("/n");
SW.WriteLine("b");
SW.WriteLine("/n");
SW.WriteLine("c");
SW.WriteLine("/n");
SW.WriteLine("d");
}
I think you might want to try declaring a string than saving it if that would hep.
StreamWriter SW = new StreamWriter(" path to file ");
string s = "a
b
c
d";
SW.WriteLine(s);

c# , Winform application -search for specific line and replace it with other line

I have a small winform app with a button, which, when clicked, I want to search a text file (file.txt) for a specific word and replace the entire line on which it was found by something else.
Let's say my text file is:
ohad yes no
box cat dog
etc...
I want to search for ohad and once find it replace the line "ohad yes no" to new line "yes I did it"
so the txt file will be:
yes I did it
box cat dog
etc...
This is my code so far:
string lineX;
StringBuilder sb = new StringBuilder();
using (System.IO.StreamReader file = new System.IO.StreamReader(textBox20.Text))
{
while ((lineX = file.ReadLine()) != null)
{
if (lineX.Contains("SRV"))
{
sb.AppendLine(lineX.ToString());
}
}
}
StreamReader streamReader;
streamReader = File.OpenText(textBox20.Text);
string contents = streamReader.ReadToEnd();
streamReader.Close();
StreamWriter streamWriter = File.CreateText(textBox20.Text);
streamWriter.Write(contents.Replace(sb.ToString(), textBox26.Text + textBox29.Text + textBox30.Text + textBox27.Text + textBox28.Text));
streamWriter.Close();
Thanks you all in advance
Ohad
Try this:
// Read file into a string array (NOTE: You should check if exists first!)
string[] Lines = File.ReadAllLines(textBox20.Text);
for(int i=0;i<Lines.Length;i++) {
if(Lines[i].Contains("SRV")) {
Lines[i] = "New value for line";
// if you only want to replace one line, uncomment the next row:
// break;
}
}
// Write array back to file
File.WriteAllLines(textBox20.Text, Lines);
for a starter, how about following these comments i put together.
var s = #"
ohad yes no
box cat dog
";
//split string into array
//go through each item in array
//check if it contains "ohad"
//if so, replace that line with my text
//convert array to string

get data from txt file and display in a multiline text box

I have a text box called: blogPostTextBox and a file called: blogMessage.txt
This blogMessage.txt contain the 3 texts called
Message1
Message2
Message3
I want to read the data from that txt file and display the data in the blogPostTextBox using either a for loop or a while loop. Also I am required to use System.Environment.NewLine at the end of each message so that each message is displayed on a separate line in blogPostsTextBox.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
blogPostsTextBox.Text = "";
string blogMessage = File.ReadAllText(Server.MapPath("~") +
"/App_Data/blogMessages.txt");
}
}
How do I continue the codes to make it work?..Thank you guys!
string path = Server.MapPath("~") + "/App_Data/blogMessages.txt";
string blogMessage = String.Join(Environment.NewLine, File.ReadLines(path));
blogPostTextBox.Text = blogMessage;
File.ReadLines returns IEnumerable<string> with lines from file (i.e. there would be your three messages). Then I concatenate lines with String.Join - it adds new line after each line which was found in text file.
BTW why you can't simply assign content of file to textbox?
blogPostTextBox.Text = File.ReadAllText(path);
UPDATE (with loop)
string path = Server.MapPath("~") + "/App_Data/blogMessages.txt";
StringBuilder builder = new StringBuilder();
foreach(var line in File.ReadLines(path))
builder.AppendLine(line);
blogPostTextBox.Text = builder.ToString();

Categories

Resources