i want to read from a text file in C#. But I want all the lines in the file to be concatenated into one line.
for example if i have in the file as
ABCD
EFGH
I need to read ABCDEFGH as one line.
I can do this by reading one line at a time from the file and concatenating that line to a string in a loop. But are there any faster method to do this?
string.Join(" ", File.ReadAllLines("path"));
Replace " " with "" or any other alternative "line-separator"
Example file:
some line
some other line
and yet another one
With " " as separator:
some line some other line and yet another one
With "" as separator:
some linesome other lineand yet another one
Use this:
using (System.IO.StreamReader myFile = new System.IO.StreamReader("test.txt")) {
string myString = myFile.ReadToEnd().Replace(Environment.NewLine, "");
}
What is a one line for you?
If you want to put the entire content of a file into a string, you could do
string fileContent = File.ReadAllText(#"c:\sometext.txt");
If you want your string without newline characters you could do
fileContent = fileContent.Replace(Environment.NewLine, " ");
string file = File.ReadAllText("text.txt").Replace("\r\n", " ");
Related
I have written a code to add Suffix at end of each line of a multi-line String but code only appends at the end of string. I am beginner. Can somebody help me in clarifying where I am mistaken? Here is my code:
protected void Prefix_Suffix_Btn_Click(object sender, EventArgs e)
{
String txt_input = Input_id.InnerText.ToString().Trim();
String txt_suffix = Suffix_id.InnerText.ToString().Trim();
String txt_output = Output_id.InnerText.ToString().Trim();
txt_input = txt_input.Replace(txt_suffix + "\n", "\n");
txt_input = txt_input + txt_suffix;
Output_id.InnerText = txt_input;
}
Input:
Line1
Line2
Line3
Desired output:
Line1AppededText
Line2AppendedText
Line3AppendedText
Let's Split text to lines, append each line and, finally, Join into string back:
string source = string.Join(Environment.NewLine,
"Line1",
"Line2",
"Line3");
// Let's have a look at the initial string;
Console.WriteLine(source);
Console.WriteLine();
string result = string.Join(Environment.NewLine, source
.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
.Select(line => line + "AppendedText"));
Console.Write(result);
Outcome:
Line1
Line2
Line3
Line1AppendedText
Line2AppendedText
Line3AppendedText
The string of that comes out of your Input_id.InnerText is a string that consists of many lines. So if you want to append to each line, you need think of a way to treat those lines separately.
A line-end is denoted as the character '\n'. It looks like 2 characters to you, but the engine will treat it as one: line-end.
What you can do is split (break up) this string into multiple strings by snapping the string whenever you find a '\n'. You can do this by the following:
var lines = Input_id.InnerText.ToString().Split('\n');
Now lines contains an array of strings, each item in there containing a line of the input.
Now you could create a new string that will be built up by your split array as follows:
var newString = "";
foreach(var line in lines) {
newString += line + "<appendText>\n"; //note how we add the \n again since those disappeared by splitting
}
Now newString will contain the new string with each line containing the appended text.
A way shorter answer would be to for instance use the replace function like this:
var newString = Input_id.InnerText.ToString().Replace("\n", "<AppendedText>\n");
There is many ways to do what you want.
You just made a mistake when passing your values into the Replace() method. The documentation for String.Replace() defines it like this:
public string Replace (string oldValue, string newValue);
The first argument ("oldValue") should be the thing you want to replace. The second argument ("newValue") should be the thing you want to change it to. You've just got them the wrong way round. You're asking it to replace the new text (suffix and newline) with the old text (just the newline), which clearly it can't do because the suffix text doesn't exist in the string yet - and it wouldn't be logical even if it worked.
Change
txt_input = txt_input.Replace(txt_suffix + "\n", "\n");
to
txt_input = txt_input.Replace("\n", txt_suffix + "\n");
and you should be fine. As other answers alluded to, there may be nicer ways of achieving the same output, but in terms of fixing your original code this is all you should need to do.
Here's a live demo (just using console output instead of HTML elements): https://dotnetfiddle.net/jnzgUy
I have a string which has \n character in some parts. I want to write that string into text file. I try Write and WriteLine method of streamwriter and in both it writes in a single line. So, is there any simple way to write this string using its new line character or should a split it into array by \n character.
Microsoft.Win32.SaveFileDialog sfd = new Microsoft.Win32.SaveFileDialog();
sfd.Filter = "g-code|*.gcode;";
if (sfd.ShowDialog() == true)
{
string path = System.IO.Path.GetFullPath(sfd.FileName);
System.IO.StreamWriter writer = new System.IO.StreamWriter(sfd.OpenFile());
writer.Write(GcodeTxt);
writer.Dispose();
writer.Close();
MessageBox.Show("File is saved.", "Saved", MessageBoxButton.OK, MessageBoxImage.Information);
}
Sample GcodeTxt:"G21;metric is good!\n G90 ;absolute positioning\n T0 ;select new extruder\n G28 ;go home\n G92 E0 ;set extruder home\n M104 S73.0 ;set temperature\n"
And the result is;
Your GcodeTxt probably has the \n formatted as a regular string and not a special character. Even if you add \r\n to your text, it will just get formatted as regular string chars.
Use Environment.NewLine instead of \n for cross env newlines:
(#"G21;metric is good!" + Environment.NewLine + #" G90 ;...
Fix the line separator in your strings to match what the platform expects. Windows expects \r\n. Use Environment.NewLine instead of "\n". Your string has been generated in the wrong way. Fix the way it is being built.
Windows Notepad reads only CrLf (Carriage return + Line feed) line endings, which is \r\n. If you put only a line feed character (\n) then Notepad will render it as if it were written in a single line.
Try opening your file in something like Notepad++ and it should look as you want it to.
To write a Carriage return + Line feed, use Environment.NewLine instead.
The answers above are accurate. However, you should also consider using StreamWriter.WriteLine instead of StreamWriter.Write when you want to insert a newline.
https://msdn.microsoft.com/en-us/library/system.io.streamwriter.writeline(v=vs.110).aspx
I have a text file with many words separated by ;. It looks like this:
eye;hand;mouth;arms;book
three;head;legs;home
I would like to go through this file and search for the symbol ; and modify the file so that every word is transposed with line break.
Should I read the text file in a string first with,
string path = #"c:\temp\MyTest.txt";
string readText = File.ReadAllText(path);
Then check:
if readText.contains(";");
But I don't know what to do next
string readText = File.ReadAllText(path);
var result = readText.Replace(";", Environment.NewLine);
use
readText.Replace(";",Environment.NewLine)
Did you mean this?
string g = readText.Replace(";", "\n");
Using C# how can i format a given xml file into a single single line (without spaces)?
My output is giving symbols if there are spaces and new lines.
Use this:
public static string StripXmlWhitespace(string Xml)
{
Regex Parser = new Regex(#">\s*<");
Xml = Parser.Replace(Xml, "><");
return Xml.Trim();
}
You can use string's Replace method to format xmlString and then save it to output:
string singleLineXml = xml.Replace(System.Environment.NewLine, " ")
or
string singleLineXml = xml.Replace("\r\n", " ")
After removing line breaks > remove spaces:
singleLineXml.Remove(' ');
Yes #Steve Wellens, Remove(' ') is a bad idea.. let's try
singleLineXml.Replace("> <","><");
And i found relative thread, may be it helps Writing string to XML file without formatting (C#)
A label printer is controled by sending a string of raw ASCII characters (which formats a label). Like this:
string s = "\x02L\r" + "D11\r" + "ySWR\r" + "421100001100096" + date + "\r" + "421100002150096" + time + "\r" + "421100001200160" + price + "\r" + "E\r";
RawPrinterHelper.SendStringToPrinter(printerName, s);
This hardcoded variant works well.
Now I want to put the control string to a .txt file and read it during runtime. Like this:
string printstr;
TextReader tr = new StreamReader("print.txt");
printstr = tr.ReadLine();
tr.Close();
But in this case printer prints nothing.
It seems, that StreamReader adds something else to this string
(If I put the read string to a MessageBox.Show(printstr); everything looks OK. Though, this way we can not see control characters added).
What could be a solution to this problem?
Your code calls tr.ReadLine() once, but it looks like you have multiple lines in that string.
Looks like a Zebra label printer, I've had the displeasure. The first thing you need to fix is the way you generate the print.txt file. You'll need to write one line for each section of the command string that's terminated with \r. For example, your command string should be written like this:
printFile.WriteLine("\x02L");
printFile.WriteLine("D11");
printFile.WriteLine("ySWR");
printFile.WriteLine("421100001100096" + date);
printFile.WriteLine("421100002150096" + time);
printFile.WriteLine("421100001200160" + price);
printFile.WriteLine("E");
printFile.WriteLine();
Now you can use ReadLine() when you read the label from print.txt. You'll need to read multiple lines to get the complete label. I added a blank line at the end, you could use that when you read the file to detect that you got all the lines that creates the label. Don't forget to append "\r" again when you send it to the printer.
It could be that the StreamReader is reading it in an Unicode format. By the way, you are reading in only just one line...you need to iterate the lines instead...Your best bet would be to do it this way:
string printstr;
TextReader tr = new StreamReader("print.txt",System.Text.Encoding.ASCII);
printstr = tr.ReadToEnd();
tr.Close();
Or read it as a binary file and read the whole chunk into a series of bytes instead, error checking is omitted.
System.IO.BinaryReader br = new System.IO.BinaryReader(new StreamReader("print.txt", System.Text.Encoding.ASCII));
byte[] data = br.ReadBytes(br.BaseStream.Length);
br.Close();
Edit:
After rem's comment I thought it best to include this additional snippet here...this follows on from the previous snippet where the variable data is referenced...
string sData = System.Text.Encoding.ASCII.GetString(data);
Hope this helps,
Best regards,
Tom.