Getting specific value from textfile not working - c#

I have a zpllabel.txt file that I read into memory but I want to get all the ^FO values from the textfile and add to it the value that user enters to offset the printer.
^XA^MCY^PRD,D,D^MMT,N^XZ
^XA
^DFCASENEW^FS
^LH0,0
^FO33,45^A0N,90,98^FN01^FS^FX Company^FS
^FO879,28^A0N,263,214^FN02^FS^FX Product^FS
^FO30,159^A0N,90,58^FN03^FS^FX Description^FS
^FO42,321^A0N,65,68^FN04^FS^FX NumberIn^FS
^FO100,436^A0N,75,66^FN05^FS^FX SelectCode^FS
^BY6,,230^FO260,252^BCN,,N,N,N,N^FN06^FS^FX RotationProduct^FS
^FO660,503^A0N,32,98^FN07^FS^FX RotationProduct^FS
^BY4,3.0,204^FO60,518^B2N,,N,N,N^FN08^FS^FX UPCCode^FS
^FO170,732^A0N,24,47^FN09^FS^FX UPCCode^FS
^FO32,516^GB590,0,10^FS
^FO32,717^GB590,0,10^FS
^FO640,573^A0N,226,212^FN10^FS^FX Rotation^FS
^FO1362,546^A0N,90,66^FDBest Before^FS
^FO1235,628^A0N,134,140^FN11^FS^FX BestBefore^FS
^FO55,391^A0N,43,77^FDSEL^FS
^FO30,267^A0N,54,100^FDQTY^FS
^XZ
^XA^XFCASENEW
^FN01^FDCompany^FS
^FN02^FDProduct^FS
^FN03^FDDescription^FS
^FN04^FDNumberIn^FS
^FN05^FDSelectCode^FS
^FN06^FDRotationProduct^FS
^FN07^FD^FS
^FN08^FDUPCCode^FS
^FN09^FD^FS
^FN10^FDRotation^FS
^FN11^FDBestBefore^FS
^PQ1,0,1,Y
^XZ
^XA^ID*.*^XZ
so for example 5th line of the label needs to be FO43 if the user enters an offset value of 10 and needs to be 23 if he enters -10 as the offset value, I am a noob at handling textfiles in c# please help
I have this code that replaces a pair of text:
try
{
byte[] file = File.ReadAllBytes("C:\\Users\\something\\Documents\\Visual Studio 2013\\Projects\\zplTest\\zplTest\\zpllabel3.txt");
using (MemoryStream memory = new MemoryStream(file))
{
using (TextReader reader = new StreamReader(memory))
{
string input = reader.ReadToEnd();
// for (int i = 0; 1 < file.Length; i++)
{
using (MemoryStream writermemory = new MemoryStream())
using (StreamWriter writer = new StreamWriter(writermemory))
{
Dictionary<string, string> replacementcollections =
new Dictionary<string, string>();
replacementcollections.Add
("^FN01^FDCompany^FS", compname);
replacementcollections.Add
("^FN02^FDProduct^FS", stlabel23);
replacementcollections.Add
("^FN03^FDDescription^FS", stlabel24);
replacementcollections.Add
("^FN04^FDNumberIn^FS", stlabel25);
replacementcollections.Add
("^FN05^FDSelectCode^FS", stlabel26);
replacementcollections.Add
("^FN06^FDRotationProduct^FS", stlabel27);
replacementcollections.Add
("^FN07^FD^FS", stlabel28);
replacementcollections.Add
("^FN08^FDUPCCode^FS", stlabel29.TrimEnd());
replacementcollections.Add
("^FN09^FD^FS", stlabel30.TrimEnd());
replacementcollections.Add
("^FN10^FDRotation^FS", "^FN10^FD" + TxtRotcode.Text.Trim() + "^FS");
replacementcollections.Add
("^FN11^FDBestBefore^FS", "^FN11^FD" + TxtBestBefore.Text.Trim() + "^FS");
replacementcollections.Add
("^PQ1,0,1,Y", "PQ" + TxtQty.Text.Trim() + ",0,1,Y");
string output = input;
foreach (KeyValuePair<string, string>
replacement in replacementcollections)
{ output = output.Replace(replacement.Key, replacement.Value); }
Label256.Visible = true;
zplcode.Text = output;
zplcode.Visible = true;
writer.Close();
ZplPreview();
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace.ToString());
Console.WriteLine(ex.Message.ToString());
}
so what I would like to accomplish
1) read text file into memory
2) find all the values of "FO"
3) add or subtract that value with what the user enters
4) send it to the textbox
5) I later send that text to the zebra printer
I tried:
using
(TextReader reader = new StreamReader(memory))
{
int offset = Convert.ToInt32(txtOffSet.Text);
string inputs = reader.ReadToEnd();
Regex r = new Regex("\\^FO([0-9]*)", RegexOptions.Singleline);
string res = r.Replace(Convert.ToString(reader), (input) => "^FO" + (int.Parse(input.Groups[1].Value) + offset).ToString());
// for (int i = 0; 1 < file.Length; i++)
{

Ok, your question is really vague and your code has nothing to do with what you asked, but this can help you on the replacement you requested.
string fileContent = File.ReadAllText("path/to/your/file");
int offset = 10; //Store here your offset, positive to add it, negative to subtract it
Regex r = new Regex("\\^FO([0-9]*)", RegexOptions.Singleline);
string res = r.Replace(fileContent, (input) => "^FO" + (int.Parse(input.Groups[1].Value) + offset).ToString());
//Now you have the content of the file with the FO replaced with it's new values
Debug.Write(res);

Related

Read PDF Line By Line using iText7 and Fill on Textboxes Winforms

I am working on a WinForms application. I use the pdf file to reset the password and the values on pdf are stored as key-value pairs(email: xxxx#mail.com, pass: 11111).
What I want to do:
Read the PDF file line by line and fill the appropriate textboxes.
What I Have done:
public bool CreatePDF(string location, string email, string key)
{
if(location != "" && email != "" && key != "")
{
PdfWriter pdfwriter = new PdfWriter(location);
PdfDocument pdf = new PdfDocument(pdfwriter);
Document document = new Document(pdf);
Paragraph fields = new Paragraph("Email: "+email + "\n" + "Secret Key: "+key);
document.Add(fields);
document.Close();
return true;
}
else
{
return false;
}
}
public string ReadPDF(string location)
{
var pdfDocument = new PdfDocument(new PdfReader(location));
StringBuilder processed = new StringBuilder();
var strategy = new LocationTextExtractionStrategy();
string text = "";
for (int i = 1; i <= pdfDocument.GetNumberOfPages(); ++i)
{
var page = pdfDocument.GetPage(i);
text += PdfTextExtractor.GetTextFromPage(page, strategy);
processed.Append(text);
}
return text;
}
}
Thank you in advance Guys!. Any suggestions on CreatePDF are also welcome.
This is what I came up with,
var pdfDocument = new PdfDocument(new PdfReader("G:\\Encryption_File.pdf"));
StringBuilder processed = new StringBuilder();
var strategy = new LocationTextExtractionStrategy();
string text = "";
for (int i = 1; i <= pdfDocument.GetNumberOfPages(); ++i)
{
var page = pdfDocument.GetPage(i);
text += PdfTextExtractor.GetTextFromPage(page, strategy);
processed.Append(text);
}
text.Split('\n');
string line = "";
line = text + "&";
string[] newLines = line.Split('&');
textBox1.Text = newLines[0].Split(':')[1].ToString();
textBox2.Text = newLines[0].Split(':')[2].ToString();

Fastest way to fuzzy match two csv files

I have written a very simple program using a nuget package in c# to read in 2 csv files and fuzzy match them and output a new csv file with all the matches. The problem is i need the program to be able to read and compare files up to 700k and comparw it to 100k. I havent been able to find a way to speed up the process. Is there any way i can do this? I will even use another language if need be.
you can ignore all the commented code its just there for when i was using it for testing purposes. sorry im a newer programmer.
the read csv funciton is for reading in the csv. the rest is code inside another function where i pass in the string arrays to pass them through fuzzymatch
static string[] ReadCSV(string path)
{
List<string> name = new List<string>();
List<string> address = new List<string>();
List<string> city = new List<string>();
List<string> state = new List<string>();
List<string> zip = new List<string>();
using (var reader = new StreamReader(path))
{
reader.ReadLine();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
name.Add(values[0] +", "+ values[1]);
//address.Add(values[1]);
//city.Add(values[2]);
//state.Add(values[3]);
//zip.Add(values[4]);
}
}
string[] name1 = name.ToArray();
return name1;
//foreach (var item in name)
//{
// Console.WriteLine(item.ToString());
//}
}
StringBuilder csvcontent = new StringBuilder();
string csvpath = #"C:\Users\bigel\Documents\outputtest.csv";
csvcontent.AppendLine("Name,Address,Match");
//Console.WriteLine("Levenshtein Edit Distance:");
int x = 1;
foreach (var name in string1)
{
for (int i = 0; i < length; i++)
{
int leven = match[i].LevenshteinDistance(name);
//Console.WriteLine(match[i] + "\t{0} against {1}", leven, name);
if (leven <= 7)
{
output[i] = input[i] + ",match";
csvcontent.AppendLine(output[i]);
//Console.WriteLine(match[i] + " " + leven + " against " + name + " is a Match");
//Console.WriteLine(output[i]);
}
else
{
if (i == 500)
{
Console.WriteLine(x);
x++;
}
}
}
}
File.AppendAllText(csvpath, csvcontent.ToString());

Using C# how can I split a text file into multiple files

How can I split a text file that contains ASCII code SOH and ETX into multiple files?
For exmaple the text file I have named 001234.txt contains the following content:
SOH{ABCDXZY}ETX
SOH{ABCDXZY}ETX
SOH{ABCDXZY}ETX
I would like to split the single text file into multiple text files for each ASCII code that starts with SOH and ends with ETX.
The single text file name should be splitted into 101234.txt , 111234.txt..etc and each contains a single content that starts with SOH and ends with ETX.
I appreciate any help.
using System.IO;
using System.Linq;
namespace ASCII_Split
{
class Program
{
static void Main(string[] args)
{
var txt = "";
const char soh = (char)1;
const char eox = (char)3;
var count = 1;
var pathToFile = #"‪‪C:\Temp\00599060.txt";
using (var sr = new StreamReader(pathToFile))
txt = sr.ReadToEnd();
while (txt.Contains(soh))
{
var outfil = Path.Combine(Path.GetDirectoryName(pathToFile), count.ToString("000"), "_fix.txt");
var eInd = txt.IndexOf(eox);
using (var sw = new StreamWriter(outfil, false))
{
sw.Write(txt.Substring(1, eInd - 1));
}
txt = txt.Substring(eInd + 1);
count++;
}
}
}
}
This should more or less do the trick:
//Read all text from file into a string
var fileContent = File.ReadAllText("001234.txt");
//split text into array according to a Regex pattern
var pattern = #"SOH*ETX";
var splitContent = Regex.Split(fileContent, pattern);
//counter for file names
var counter = 10;
foreach(var content in splitContent)
{
//create file and use stream to write to it
using (var stream = File.Create($"{counter++}1234.txt"))
{
var contentAsBytes = new UTF8Encoding(true).GetBytes(content);
stream.Write(contentAsBytes, 0, contentAsBytes.Length);
}
}
Provided by SOH and ETX you mean the respective control characters, this here should get you on your way:
var txt = "";
const char soh = (char) 1;
const char eox = (char) 3;
var count = 1;
var pathToFile = #"C:\00_Projects_temp\test.txt";
using (var sr = new StreamReader(pathToFile))
txt = sr.ReadToEnd();
while (txt.Contains(soh))
{
var outfil = Path.Combine(Path.GetDirectoryName(pathToFile), count.ToString("000"), "_test.txt");
var eInd = txt.IndexOf(eox);
using (var sw = new StreamWriter(outfil, false))
{
sw.Write(txt.Substring(1, eInd - 1));
}
txt = txt.Substring(eInd + 1);
count++;
}
Thank you LocEngineer the program works, I did little change to concatonate the filename with the counter using "+" instead of ",".
using System.IO;
using System.Linq;
namespace ASCII_Split
{
class Program
{
static void Main(string[] args)
{
var txt = "";
const char soh = (char)1;
const char eox = (char)3;
var count = 1;
var pathToFile = #"C:\Temp\00599060.txt";
using (var sr = new StreamReader (pathToFile))
txt = sr.ReadToEnd();
if (txt.IndexOf(soh) != txt.LastIndexOf(soh))
{
while (txt.Contains(soh))
{
var outfil = Path.Combine(Path.GetDirectoryName(pathToFile), count.ToString("00") + Path.GetFileName(pathToFile));
var eInd = txt.IndexOf(eox);
using (var sw = new StreamWriter(outfil, false))
{
sw.Write(txt.Substring(1, eInd - 1));
}
txt = txt.Substring(eInd + 1);
count++;
}
File.Move((pathToFile), (pathToFile) + ".org");
}
}
}
}

Union of million line urls in 2 files

File A B contains million urls.
1, go through the url in file A one by one.
2, extract subdomain.com (http://subdomain.com/path/file)
3, if subdomain.com exist file B, save it to file C.
Any quickest way to get file C with c#?
Thanks.
when i use readline, it have no much different.
// stat
DateTime start = DateTime.Now;
int totalcount = 0;
int n1;
if (!int.TryParse(num1.Text, out n1))
n1 = 0;
// memory
dZLinklist = new Dictionary<string, string>();
// read file
string fileName = openFileDialog1.FileName; // get file name
textBox1.Text = fileName;
StreamReader sr = new StreamReader(textBox1.Text);
string fullfile = File.ReadAllText(#textBox1.Text);
string[] sArray = fullfile.Split( '\n');
//IEnumerable<string> sArray = tool.GetSplit(fullfile, '\n');
//string sLine = "";
//while (sLine != null)
foreach ( string sLine in sArray)
{
totalcount++;
//sLine = sr.ReadLine();
if (sLine != null)
{
//string reg = "http[s]*://.*?/";
//Regex R = new Regex(reg, RegexOptions.Compiled);
//Match m = R.Match(sLine);
//if(m.Success)
int length = sLine.IndexOf(' ', n1); // default http://
if(length > 0)
{
//string urls = sLine.Substring(0, length);
dZLinklist[sLine.Substring(0,length)] = sLine;
}
}
}
TimeSpan time = DateTime.Now - start;
int count = dZLinklist.Count;
double sec = Math.Round(time.TotalSeconds,2);
label1.Text = "(" + totalcount + ")" + count.ToString() + " / " + sec + " = " + (Math.Round(count / sec,2)).ToString();
sr.Close();
I would go for using Microsoft LogParser for processing big files: MS LogParser. Are you limited to implement it in described way only?

Serial Port reads fine but assigned string has junk, C#

I am trying to split the incoming data from a Serial Port, and update text boxes with subsequent data. I first see if a split on '$' is possible, and if the next word after splitting is "GPGGA". If yes, I would like to extract data from this sentence where ',' serves as the separator.
Now, as you see, I update the entire data read by the Serial Port first, and this works fine. The full sentence containing the "GPGGA" line is displayed. But after I split it, the part of the sentence that contains the "GPGGA" looks something like this"GPGGA,1\0\0\0\0\0..." when really the sentence that was just updated to the text box before was "GPGGA,160333,,,......". I am absolutely certain that there is a value after GPGGA in the sentence but when i try to look at it in the debug mode, the string 'ser_data', and hence its subsequent substrings all show the same junk. So, the final text box that I want to update inevitably ends up displaying just 1.
Could anyone tell me why this is happening, and how I can correct it. I need it urgently for my thesis work.
Thanks,
Brett
P.S: I've attached the code below.
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] bData = null;
bData = new byte[40];
serialPort.Read(bData, 0, 40);
string ser_data = System.Text.Encoding.GetEncoding("utf-8").GetString(bData);
txtAck.Invoke(new UpdateTextCallback(this.UpdateTextAck), new object[] { ser_data });
string[] str = null;
str = new string[40];
string[] str_ack = null;
str = ser_data.Split('$');
if (str.Length > 1)
{
for (int i = 1; i < str.Length; i++)
{
string temp1 = null;
temp1 = str[i];
if (temp1.StartsWith("GPGGA"))
{
string[] temp2 = null;
temp2 = temp1.Split(',');
StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
if (temp2.Length > 1)
{
string Time_GPS = temp2[1];
txtEasting.Invoke(new UpdateTextCallback(this.UpdateTextEast), new object[] { Time_GPS });
string text = "Time : " + Time_GPS;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 2)
{
string Lat = temp2[2];
txtLatitude.Invoke(new UpdateTextCallback(this.UpdateTextLat), new object[] { Lat });
string text = " Latitude : " + Lat;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 4)
{
string Long = temp2[4];
txtLongitude.Invoke(new UpdateTextCallback(this.UpdateTextLong), new object[] { Long });
string text = " Longitude : " + Long;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 9)
{
string Alt = temp2[9];
txtNorthing.Invoke(new UpdateTextCallback(this.UpdateTextNorth), new object[] { Alt });
string text = " Altitude : " + Alt;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
string Text = "." + '\n';
objWriter.WriteLine(Text);
objWriter.Close();
temp2 = null;
flag_status = 0;
}
temp1 = null;
}
}
str = null;
SerialPort.Read does not necessarily read the number of characters you ask for.
You need to save the return value, which is the number of characters read.
// nBytesRead will be between 0 and 40, depending on how many bytes were waiting.
int nBytesRead = serialPort.Read(bData, 0, 40);
// Only decode the number of bytes actually retrieved.
string ser_data = System.Text.Encoding.GetEncoding("utf-8").GetString(bData, 0, nBytesRead);
Fixed and majorly cleaned up. This assumes two things: that your encoding is really UTF-8, and that your lines end with newline characters.
private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
serialPort.Encoding = ASCIIEncoding.UTF8;
string ser_data = serialPort.ReadLine();
txtAck.Invoke(new UpdateTextCallback(this.UpdateTextAck), new object[] { ser_data });
string[] str = ser_data.Split(new char[] { '$' }, 2);
if (str.Length > 1)
{
for (int i = 1; i < str.Length; i++)
{
string temp1 = str[i];
if (temp1.StartsWith("GPGGA"))
{
StreamWriter objWriter = new StreamWriter(#"D:\Server.txt", true);
try
{
string[] temp2 = temp1.Split(',');
if (temp2.Length > 1)
{
string Time_GPS = temp2[1];
txtEasting.Invoke(new UpdateTextCallback(this.UpdateTextEast), new object[] { Time_GPS });
string text = "Time : " + Time_GPS;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 2)
{
string Lat = temp2[2];
txtLatitude.Invoke(new UpdateTextCallback(this.UpdateTextLat), new object[] { Lat });
string text = " Latitude : " + Lat;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 4)
{
string Long = temp2[4];
txtLongitude.Invoke(new UpdateTextCallback(this.UpdateTextLong), new object[] { Long });
string text = " Longitude : " + Long;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
if (temp2.Length > 9)
{
string Alt = temp2[9];
txtNorthing.Invoke(new UpdateTextCallback(this.UpdateTextNorth), new object[] { Alt });
string text = " Altitude : " + Alt;
// StreamWriter objWriter = new System.IO.StreamWriter(#"D:\Server.txt", true);
objWriter.WriteLine(text);
}
objWriter.WriteLine(".\n");
}
finally
{
objWriter.Close();
}
flag_status = 0;
}
}
}
}

Categories

Resources