How to convert NiceLabel files to text in c# - c#

I'm trying to convert thousands of .lbl files to text to extract just the data I need to populate a database for a much cheaper, easier method of printing labels. However, I've tried many different approaches to convert the .lbl file to a text file:
see this question
and this question
But I just have had zero luck. Here's the code:
using (BinaryReader b = new BinaryReader(File.Open(#"stupid.lbl", FileMode.Open)))
{
int length = (int)b.BaseStream.Length;
byte[] allData = b.ReadBytes(length);
using (BinaryWriter w = new BinaryWriter(File.Open(#"test.txt", FileMode.Create)))
{
Encoding encEncoder = Encoding.ASCII;
string str = encEncoder.GetString(allData);
w.Write(str);
}
}
I do have the proper file paths and whatnot to be able to actually read/write and everything opens, but it's all gibberish...I just need to get the real, useful, human readable text out of it to push into an access db...Any ideas out there?

Related

Saving File conversion to variable instead of physical location

I'm trying out to use the XML - Mind converter https://www.xmlmind.com/foconverter/ to convert some xsl-fo to an rtf and this works well . Just to be clear this is nothing specific to the conveter or its functionality but just a clarification I would like to get which is why I am asking this on stack overflow .
So I have the following code (that was obtained from some documentation)
string foFilePath = #"D:\Temp\test.fo";
string ourPutFilePath = #"D:\Temp\test.rtf";
Converter converter = new Converter();
converter.OutputFormat = OutputFormat.Rtf;
converter.OutputEncoding = "windows-1252";
converter.ImageResolution = 120;
converter.SetInput(foFilePath);
converter.SetOutput(ourPutFilePath);
converter.Convert();
What happens here is quite simple Reads a file from the input path and stores the converted file in the specified output . The question I would like to clarify here is , wheather it would be possible to store this content that is being saved in the file out put path within a variable as well to may be do some processing during the application runtime ?
Maybe I can use the MemoryStream for it ? I'm just not sure how to do it and would really appreciate some help here.
I understand that I can always read it back from the file output path but I am looking for something better than that as saving the file to a certain location may not always be possible in my case
EDIT :- The converter.SetOutput() method allows 3 overloads in the parameters
String fileName
Stream stream
TextWriter writer
Sine you need the output as a string you could try doing something like this
string content;
using (var stream = new MemoryStream())
{
using (var writer = new StreamWriter(stream))
{
Converter converter = new Converter();
converter.OutputFormat = OutputFormat.Rtf;
converter.OutputEncoding = "windows-1252";
converter.ImageResolution = 120;
converter.SetInput(foFilePath);
converter.SetOutput(writer);
converter.Convert();
stream.Position = 0;
content = Encoding.UTF8.GetString(stream.ToArray());
}
}
I'm not sure about the Encoding though, and if the Convert() uses a different encoding this might not work

How can I write a Integer to a FileStream in C#?

I was wondering if someone can help me solve a issue I have run into while playing with FileStreams. I have been trying to send an integer, 50, to a FileStream and write its value onto a File. However, it writes 2 to the file instead of 50. I know the ASCII representation of 50 is 2, so am not sure if this is part of the issue. If anyone has any pointers, I'd really appreciate it!
Here is my relevant code:
From the main function:
string testMessage = "Testing writing some arbitrary string to a streama";
int tmL = testMessage.Length;
byte bb = Convert.ToByte(tmL);
SendByteStrem(bb);
And here is my streaming function:
public static void SendByteStrem(byte c){
using (Stream ioStream = new FileStream(#"C:\Users\db0201\Desktop\stream.txt", FileMode.OpenOrCreate)){
ioStream.WriteByte(c);
}
}
As you haven't explicitly stated your goal, i will answer the question for what it is.
The easiest way to write to a file would be to use File.WriteAllText which essentially opens a StreamWriter (which in-turn is open a FileStream) and calls Write
Creates a new file, write the contents to the file, and then closes
the file. If the target file already exists, it is overwritten.
File.WriteAllText(fileName, "50")
or
var myInt = 50;
File.WriteAllText(fileName, myInt.ToString())
If you wanted to use the StreaWriter exclusively
using (varwriter = new StreamWriter(fileName))
writer.Write(myInt.ToString());
If you wanted more configuration over the underlying FileStream
using (var writer = new StreamWriter(new FileStream(fileName, FileMode.CreateNew)))
writer.Write(myInt.ToString());
if you just want to use a FileStream then things get a bit more manual as you will need to convert things to bytes
using (var stream = new FileStream(fileName, FileMode.CreateNew))
{
var bytes = Encoding.UTF8.GetBytes(myInt.ToString());
stream.Write(bytes, 0, bytes.Length);
}

C# - Read bytes from file from a specific string

I'm trying to parse a crg-file in C#. The file is mixed with plain text and binary data. The first section of the file contains plain text while the rest of the file is binary (lots of floats), here's an example:
$
$ROAD_CRG
reference_line_start_u = 100
reference_line_end_u = 120
$
$KD_DEFINITION
#:KRBI
U:reference line u,m,730.000,0.010
D:reference line phi,rad
D:long section 1,m
D:long section 2,m
D:long section 3,m
...
$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
�#z����RA����\�l
...
I know I can read bytes starting at a specific offset but how do I find out which byte to start from? The last row before the binary section will always contain at least four dollar signs "$$$$". Here's what I've got so far:
using var fs = new FileStream(#"crg_sample.crg", FileMode.Open, FileAccess.Read);
var startByte = ??; // How to find out where to start?
using (BinaryReader reader = new BinaryReader(fs))
{
reader.BaseStream.Seek(startByte, SeekOrigin.Begin);
var f = reader.ReadSingle();
Debug.WriteLine(f);
}
When you have a mixture of text data and binary data, you need to treat everything as binary. This means you should be using raw Stream access, or something similar, and using binary APIs to look through the text data (often looking for cr/lf/crlf at bytes as sentinels, although it sounds like in your case you could just look for the $$$$ using binary APIs, then decode the entire block before, and scan forwards). When you think you have an entire line, then you can use Encoding to parse each line - the most convenient API being encoding.GetString(). When you've finished looking through the text data as binary, then you can continue parsing the binary data, again using the binary API. I would usually recommend against BinaryReader here too, because frankly it doesn't gain you much over more direct API. The other problem you might want to think about is CPU endianness, but assuming that isn't a problem: BitConverter.ToSingle() may be your friend.
If the data is modest in size, you may find it easiest to use byte[] for the data; either via File.ReadAllBytes, or by renting an oversized byte[] from the array-pool, and loading it from a FileStream. The Stream API is awkward for this kind of scenario, because once you've looked at data: it has gone - so you need to maintain your own back-buffers. The pipelines API is ideal for this, when dealing with large data, but is an advanced topic.
UPDATE: This code may not work as expected. Please review the valuable information in the comments.
using (var fs = new FileStream(#"crg_sample.crg", FileMode.Open, FileAccess.Read))
{
using (StreamReader sr = new StreamReader(fs, Encoding.ASCII, true, 1, true))
{
var line = sr.ReadLine();
while (!string.IsNullOrWhiteSpace(line) && !line.Contains("$$$$"))
{
line = sr.ReadLine();
}
}
using (BinaryReader reader = new BinaryReader(fs))
{
// TODO: Start reading the binary data
}
}
Solution
I know this is far from the most optimized solution but in my case it did the trick and since the plain text section of the file was known to be fairly small this didn't cause any noticable performance issues. Here's the code:
using var fileStream = new FileStream(#"crg_sample.crg", FileMode.Open, FileAccess.Read);
using var reader = new BinaryReader(fileStream);
var newLine = '\n';
var markerString = "$$$$";
var currentString = "";
var foundMarker = false;
var foundNewLine = false;
while (!foundNewLine)
{
var c = reader.ReadChar();
if (!foundMarker)
{
currentString += c;
if (currentString.Length > markerString.Length)
currentString = currentString.Substring(1);
if (currentString == markerString)
foundMarker = true;
}
else
{
if (c == newLine)
foundNewLine = true;
}
}
if (foundNewLine)
{
// Read binary
}
Note: If you're dealing with larger or more complex files you should probably take a look at Mark Gravell's answer and the comment sections.

Two identical files have different file size based on the way it is written from C#

I am trying to write to a file an array of object serialised into JSON format. I am trying to write it in two different way as shown below.
ToSerialise[] Obj = new ToSerialise[10];
for (int i = 0; i < 10; i++)
{
Obj[i] = new ToSerialise();
}
//First form of serialising
UnicodeEncoding uniEncoding = new UnicodeEncoding();
String SerialisedOutput;
SerialisedOutput = JsonConvert.SerializeObject(Obj, Formatting.Indented);
FileStream fs1 = new FileStream(#"C:\file1.log", FileMode.CreateNew);
fs1.Write(uniEncoding.GetBytes(SerialisedOutput), 0, uniEncoding.GetByteCount(SerialisedOutput));
fs1.Close();
//Second form of serialising
FileStream fs2 = new FileStream(#"C:\file2.log", FileMode.CreateNew);
StreamWriter sw = new StreamWriter(fs2);
JsonWriter jw = new JsonTextWriter(sw);
JsonSerializer js = new JsonSerializer();
jw.Formatting = Formatting.Indented;
js.Serialize(jw, Obj);
jw.Close();
fs2.Close();
Even though the content of both the files are same, they have different file size. Actually the first file is exactly twice the size of the second file. I tried comparing the output using textpad and it says they are excatly the same. Why do they have different file size?
I am running this on Windows 7 32 bit, .Net4
Thanks
Even though the content of both the files are same, they have different file size.
If they have a different size, then they definitely have different contents. A file is (pretty much) just a sequence of bytes - and if two sequences have different lengths, they're different sequences.
In this case, the two files both represent the same text, but using different encodings - file2 will use UTF-8, and file1 will use UTF-16.
To think of it a different way: if you saved the same picture to two files, one as JPEG and one as PNG, would you expect the files to be the same size?

why wont XML read from string? (but will from .txt of same data)

this is the code in question:
using (var file = MemoryMappedFile.OpenExisting("AIDA64_SensorValues"))
{
using (var readerz = file.CreateViewAccessor(0, 0))
{
var bytes = new byte[567];
var encoding = Encoding.ASCII;
readerz.ReadArray<byte>(0, bytes, 0, bytes.Length);
File.WriteAllText("C:\\myFile.txt", encoding.GetString(bytes));
var readerSettings = new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment };
using (var reader = XmlReader.Create("C:\\myFile.txt", readerSettings))
{
This is what myfile.txt looks like:
<sys><id>SCPUCLK</id><label>CPU Clock</label><value>1598</value></sys><sys><id>SCPUFSB</id><label>CPU FSB</label><value>266</value></sys><sys><id>SMEMSPEED</id><label>Memory Speed</label><value>DDR2-667</value></sys><sys><id>SFREEMEM</id><label>Free Memory</label><value>415</value></sys><sys><id>SGPU1CLK</id><label>GPU Clock</label><value>562</value></sys><sys><id>SFREELVMEM</id><label>Free Local Video Memory</label><value>229</value></sys><temp><id>TCPU</id><label>CPU</label><value>42</value></temp><temp><id>TGPU1</id><label>GPU</label><value>58</value></temp>
if i write the data to a txt file on the hard drive with:
File.WriteAllText("C:\\myFile.txt", encoding.GetString(bytes));
then read that same text file with the fragment XmlReader:
XmlReader.Create("C:\\myFile.txt");
it reads it just fine, the program runs and completes like it supposed to, but then if i directly read with the fragment XmlReader like:
XmlReader.Create(encoding.GetString(bytes));
I get exception when run " illegal characters in path" on the XmlReader.Create line.
ive tried writing it to a separate string first and reading that with xmlreader, and it wouldn't help to try to print it to CMD to see what it looks like because CMD wouldnt show the invalid characters im dealing with right?
but oh well i did Console.WriteLine(encoding.GetString(bytes)); and it precisely matched the txt file.
so somehow writing it to the text file is removing some "illegal characters"? what do you guys think?
XmlReader.Create(encoding.GetString(bytes));
XmlReader.Create() interprets your string as the URI where it should read a file from. Instead encapsulate your bytes in a StringReader:
StringReader sr = new StringReader(encoding.GetString(bytes));
XmlReader.Create(sr);
Here:
XmlReader.Create(encoding.GetString(bytes));
you are simply invoking the following method which takes a string representing a filename. However you are passing the actual XML string to it which obviously is an invalid filename.
If you want to load the reader from a buffer you could use a stream:
byte[] bytes = ... represents the XML bytes
using (var stream = new MemoryStream(bytes))
using (var reader = XmlReader.Create(stream))
{
...
}
The method XmlReader.Create() with a single string as argument needs a URI passed and not the XML document as string, please refer to the MSDN. It tries to open a file named "<..." which is an invalid URI. You can pass a Stream instead.
You are passing the xml content in the place where it is expecting a path, as evidenced by the error - illegal characters in path
Use an appropriate overload, and pass a stream - http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.create.aspx

Categories