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.
Related
My client requirment has fixed length file records in the format of header, body and footer but in the footer they wants to have an empty space of 1966 lenght . I tried this using difffent butttons for header and footer and body but was unable to specify space at the end. this was my code .. space is not working in this while creating footer.
FileStream fs = new FileStream(#"C:\Users\IT-Administrator\Desktop\ee.txt", FileMode.Open, FileAccess.ReadWrite);
fs.Seek(0, SeekOrigin.End);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(comboBox6.Text + textBox2.Text + textBox3.Text + textBox4.Text + **SPACE(1966)** );
sw.Close();
fs.Close();**strong text**
Use String.PadRight() to pad the string.
Say for example the max string length was 2000 characters, you can do something like this:
string example = "Example";
string full_example = example.PadRight(2000);
This will take the length of the original string and pad it out with spaces until it reaches the desired width.
In your case if you wanted exactly 1966 spaces though you can do this:
string spaces = String.Empty.PadRight(1966);
You can do this by using the overload of WriteLine that accepts a format specifier.
If you want the last element to take a total of 1966 characters, you can write :
using(var sw=new StreamWriter(#"C:\Users\IT-Administrator\Desktop\ee.txt"))
{
sw.WriteLine("{0}{1}{2}{3,-1966}",comboBox6.Text ,textBox2.Text,
textBox3.Text,textBox4.Text );
}
This way it's much easier to see what the actual string will look like. For example, you can see that you are actually joining all elements in one continuous string. Perhaps, what you wanted to do was to separate them by spaces, eg: "{0} {1} {3} {4,-1966}"
If you want the the last element to be followed by 1966 spaces:
using(var sw=new StreamWriter(#"C:\Users\IT-Administrator\Desktop\ee.txt"))
{
sw.WriteLine("{0}{1}{3}{4}{5,-1966}",comboBox6.Text ,textBox2.Text,
textBox3.Text,textBox4.Text,' ');
}
In the above code, using makes sure the StreamWriter will close even if an exception occurs. The code also avoids creating both a StreamWriter and FileStream by creating the StreamWriter with a path argument
If you want to create a string consisting of 1966 spaces, you can use the string constructor that takes a character and a number of times to repeat it: new String(' ', 1966).
If you want to pad strings out to a particular length, you can use PadRight or PadLeft as appropriate.
In my page I will get the ID from link parameters, with that ID I will search the database for the file path, after reading the file and storing its contents I want to put its contents inside my <pre> tag... So I will have a literal in which the text for it will be:
Code.Text = "<pre>" + File Contents in string + "</pre>";
My question is how will I insert the contents there if I need to read the file line by line into an string array, unless I read it all into one string, BUT that will make the text look like one huge line in the page.
Also, is it going to conflict with literal syntax(?) definitions, since for quotes we have to do \" instead of " ...?
If you are working with literal control, you use the StringBiulder And Append properties becouse It let you put any HTML code from code behind.
Something like:
//Declare your String Builder
private StringBuilder stb = new StringBuilder();
And also you could have any proccess when you read the file, and split it by any char like \n
string readFile = //Any Method that you read you file string.
string[] tokens = readFile.Split('\n');
stb.Append("<pre>");
foreach (string s in tokens)
{
stb.Append( s + "<\br>");
}
stb.Append("</pre>");
finally you attach the Stringbuilder value to you Literal
YourLiteral.Text = stb.ToString();
I hope that help, and you won't have the value in one line. And remember the carring return need be in the string file to the split works.
Cheers
If I asked the question "how to read a file into a string" the answer would be obvious. However -- here is the catch with CR/LF preserved.
The problem is, File.ReadAllText strips those characters. StreamReader.ReadToEnd just converted LF into CR for me which led to long investigation where I have bug in pretty obvious code ;-)
So, in short, if I have file containing foo\n\r\nbar I would like to get foo\n\r\nbar (i.e. exactly the same content), not foo bar, foobar, or foo\n\n\nbar. Is there some ready to use way in .Net space?
The outcome should be always single string, containing entire file.
Are you sure that those methods are the culprits that are stripping out your characters?
I tried to write up a quick test; StreamReader.ReadToEnd preserves all newline characters.
string str = "foo\n\r\nbar";
using (Stream ms = new MemoryStream(Encoding.ASCII.GetBytes(str)))
using (StreamReader sr = new StreamReader(ms, Encoding.UTF8))
{
string str2 = sr.ReadToEnd();
Console.WriteLine(string.Join(",", str2.Select(c => ((int)c))));
}
// Output: 102,111,111,10,13,10,98,97,114
// f o o \n \r \n b a r
An identical result is achieved when writing to and reading from a temporary file:
string str = "foo\n\r\nbar";
string temp = Path.GetTempFileName();
File.WriteAllText(temp, str);
string str2 = File.ReadAllText(temp);
Console.WriteLine(string.Join(",", str2.Select(c => ((int)c))));
It appears that your newlines are getting lost elsewhere.
This piece of code will preserve LR and CR
string r = File.ReadAllText(#".\TestData\TR120119.TRX", Encoding.ASCII);
The outcome should be always single string, containing entire file.
It takes two hops. First one is File.ReadAllBytes() to get all the bytes in the file. Which doesn't try to translate anything, you get the raw data in the file so the weirdo line-endings are preserved as-is.
But that's bytes, you asked for a string. So second hop is to apply Encoding.GetString() to convert the bytes to a string. The one thing you have to do is pick the right Encoding class, the one that matches the encoding used by the program that wrote the file. Given that the file is pretty messed up if it contains \n\r\n sequences, and you didn't document anything else about the file, your best bet is to use Encoding.Default. Tweak as necessary.
You can read the contents of a file using File.ReadAllLines, which will return an array of the lines. Then use String.Join to merge the lines together using a separator.
string[] lines = File.ReadAllLines(#"C:\Users\User\file.txt");
string allLines = String.Join("\r\n", lines);
Note that this will lose the precision of the actual line terminator characters. For example, if the lines end in only \n or \r, the resulting string allLines will have replaced them with \r\n line terminators.
There are of course other ways of acheiving this without losing the true EOL terminator, however ReadAllLines is handy in that it can detect many types of text encoding by itself, and it also takes up very few lines of code.
ReadAllText doesn't return carriage returns.
This method opens a file, reads each line of the file, and then adds each line as an element of a string. It 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. The resulting string does not contain the terminating carriage return and/or line feed.
From MSDN - https://msdn.microsoft.com/en-us/library/ms143368(v=vs.110).aspx
This is similar to the accepted answer, but wanted to be more to the point. sr.ReadToEnd() will read the bytes like is desired:
string myFilePath = #"C:\temp\somefile.txt";
string myEvents = String.Empty;
FileStream fs = new FileStream(myFilePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
myEvents = sr.ReadToEnd();
sr.Close();
fs.Close();
You could even also do those in cascaded using statements. But I wanted to describe how the way you write to that file in the first place will determine how to read the content from the myEvents string, and might really be where the problem lies. I wrote to my file like this:
using System.Reflection;
using System.IO;
private static void RecordEvents(string someEvent)
{
string folderLoc = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (!folderLoc.EndsWith(#"\")) folderLoc += #"\";
folderLoc = folderLoc.Replace(#"\\", #"\"); // replace double-slashes with single slashes
string myFilePath = folderLoc + "myEventFile.txt";
if (!File.Exists(myFilePath))
File.Create(myFilePath).Close(); // must .Close() since will conflict with opening FileStream, below
FileStream fs = new FileStream(myFilePath, FileMode.Append);
StreamWriter sr = new StreamWriter(fs);
sr.Write(someEvent + Environment.NewLine);
sr.Close();
fs.Close();
}
Then I could use the code farther above to get the string of the contents. Because I was going further and looking for the individual strings, I put this code after THAT code, up there:
if (myEvents != String.Empty) // we have something
{
// (char)2660 is ♠ -- I could have chosen any delimiter I did not
// expect to find in my text
myEvents = myEvents.Replace(Environment.NewLine, ((char)2660).ToString());
string[] eventArray = myEvents.Split((char)2660);
foreach (string s in eventArray)
{
if (!String.IsNullOrEmpty(s))
// do whatever with the individual strings from your file
}
}
And this worked fine. So I know that myEvents had to have the Environment.NewLine characters preserved because I was able to replace it with (char)2660 and do a .Split() on that string using that character to divide it into the individual segments.
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", " ");
hoping you can help
I have the following code
List<string> comconfig = populate.resolveconfig(_varibledic, populate.GetVaribles[0].Substring(populate.GetVaribles[0].IndexOf("=") + 1)); //get the aray of strings
string config = ""; //create a empty otput string
config = #"\rtf1\ansi\deff0\deftab240 {\fonttbl {\f000 Monaco;} {\f001 Monaco;} } {\colortbl \red255\green255\blue255; \red000\green000\blue000; \red255\green255\blue255; \red000\green000\blue000; }";
config = config + #"\f96\fs20\cb3\cf2 \highlight1\cf0 "; // assigned rtf header to output string
foreach (var strings in comconfig) //loop though array adding to output string
{
config = config + strings + #"\par ";
}
config = config + "}"; //close of RTF code
So trying to create a RTF string that I can later display. comconfig is an array of strings with some RTF mark up for highlighting and stuff.
trouble is that if I use # then I get double \ which mess up the RTF, and if i dont use them, then the escape charatures mess up the code??
what is the best way to build up this string by adding a preformated RTF header and the aray of strings in the middle. it is displayed finaly in a RTF.textbox. or converted to a plain text string at the users request. I need to ignore the escape charatures with out messing up the RTF?
Cheers
Aaron
No, you don't get a double \. You're getting confuzzled by the debugger display of the string. It shows you what the string looks like if you had written it in C# without the #. Click the spy glass icon at the far right and select the Text Visualizer.