New line in C# for Word Document - c#

how to recognize new line c# while uploading word documents..? i have to give next line as a new word in word document here what is happening means if i add three or more words in .doc in separate line its taking as one word i want to separate the words but if i give a space after a word it is taking as expected without giving space if i start a new word in new line its taking as one word
money
power
cash
moneypowercash
like this iam getting here if i give space after these words its getting as expected
how to resolve this issue here i will give my code to generating this keyword
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
if (cmbDepartment.SelectedValue != "0" && cmbDocumentType.SelectedValue != "0")
{
TodayDate = DateTime.Today.ToString("yyyy-MM-dd");
TempFolder = System.Configuration.ConfigurationManager.AppSettings["TempWorkFolder"];
TextReader reader = new FilterReader(TempFolder + Session["EncyptImgName"]);
StringBuilder Keywords = new StringBuilder();
using (reader)
{
Keywords = Keywords.Append(reader.ReadToEnd());
}
//remove common words
string[] removablewords = { ":", ".", "~"};
foreach (string st in removablewords)
{
Keywords.Replace(st, " ");
}
//Reomve unwated spaces
while (Keywords.ToString().Contains(" "))
{
Keywords.Replace(" ", " ");
}
string str = Keywords.ToString();
Keywords.Clear();
Keywords.Append("<words><s>" + str.Replace(" ", "</s><s>") + "</s></words>");
string xml = Keywords.ToString();
XElement items = XElement.Parse(xml);
var groups = from t in items.Descendants("s")
group t by t.Value.ToLower() into g
select new KeyFrequency(g.Key, g.Count());
groups = groups.OrderByDescending(g => g.Frequency).Take(15);
keyvalues = new List<string>();
foreach (KeyFrequency g in groups)
{
keyvalues.Add(g.Key);
}
for (key = 0; key < keyvalues.Count && key < 10; key++)
{
Button btn = (Button)pnlKeywords.FindControl("Button" + Convert.ToString(key + 1));
btn.Visible = true;
btn.Text = keyvalues[key];
btn.CommandArgument = keyvalues[key];
}
if (key < 10)
{
for (key = key; key < 10; key++)
{
Button btn = (Button)pnlKeywords.FindControl("Button" + Convert.ToString(key + 1));
btn.Visible = false;
}
}
else
{
AsyncFileUpload1.BackColor = System.Drawing.Color.Red;
}
}
}
catch (Exception ex)
{
Button1.Text = "Keywords Not Available for This Document";
Button1.CommandArgument = null;
Button2.Visible = false;
Button3.Visible = false;
Button4.Visible = false;
Button5.Visible = false;
Button6.Visible = false;
Button7.Visible = false;
Button8.Visible = false;
Button9.Visible = false;
Button10.Visible = false;
}
}

For each new line, try replacing \n with "</w:t><w:br/><w:t>". It worked for me.
string.Replace("\n", "</w:t><w:br/><w:t>")

Related

Delete row in a CSV file and show in DataGridView using c#

I have a problem when I want to delete a row in a CSV File, I have this code but only deletes the field that contains the line.
Example:
CSV File:
ID,Name,Lastname,Country
1,David,tod,UK
2,Juan,Perez,Germ
3,Pepe,Lopez,Col
First iteration, sending the id 1 to delete the line:
ID,Name,Lastname,Country
David,tod,UK
2,Juan,Perez,Germ
3,Pepe,Lopez,Arg
Just delete the id I want, but not the whole line
The expected result would be that like this:
ID,Name,Lastname,Country
2,Juan,Perez,Arg
3,Pepe,Lopez,Col
this is my code, What am I doing wrong? I have never used csv in C# :(
string searchid = "1";
string[] values = File.ReadAllText("C:\\registros.csv").Split(new char[] { ',' });
StringBuilder ObjStringBuilder = new StringBuilder();
for (int i = 0; i < values.Length; i++)
{
if (values[i].Contains(searchid))
continue;
ObjStringBuilder.Append(values[i] + ",");
}
ObjStringBuilder.ToString().Remove(ObjStringBuilder.Length - 1);
File.WriteAllText("\\registros.csv", ObjStringBuilder.ToString());
Another question is how can I show the CSV file in a datagridview in Windows Forms. I have this logic, don't know if this is correct, but how I can show it?
public DataTable ConvertCSVtoDataTable()
{
StreamReader sr = new StreamReader("\\registros.csv");
string[] headers = sr.ReadLine().Split(',');
DataTable dt = new DataTable();
foreach (string header in headers)
{
dt.Columns.Add(header);
}
while (!sr.EndOfStream)
{
string[] rows = Regex.Split(sr.ReadLine(), ",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");
DataRow dr = dt.NewRow();
for (int i = 0; i < headers.Length; i++)
{
dr[i] = rows[i];
}
dt.Rows.Add(dr);
}
return dt;
}
Thanks!
You can delete row from CSV using below link
Delete rows from CSV
and
You can convert the CSV into DataTable using the below code. If your csv file uses delimiter as ,
public DataTable ReadCSV(String FilePath, Boolean IsHeader)
{
string strConn = null;
string folderpath = null;
try
{
folderpath = FilePath.Substring(0, FilePath.LastIndexOf("\\") + 1);
string FileName = Path.GetFileName(FilePath);
if (IsHeader == true)
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + folderpath + ";" + "Extended Properties=\"text;HDR=YES\"";
}
else
{
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + folderpath + ";" + "Extended Properties=\"text;HDR=NO\"";
}
OleDbConnection Conn = new OleDbConnection();
Conn.ConnectionString = strConn;
Conn.Open();
string s1 = "select * from [" + FileName + "]";
OleDbDataAdapter da1 = new OleDbDataAdapter(s1, Conn);
DataSet dtall = new DataSet();
da1.Fill(dtall);
Conn.Close();
return dtall.Tables[0].Copy();
}
catch (Exception ex)
{
Exception excep = new Exception("CSV : " + ex.Message);
throw excep;
}
}
Reading and writing CSV files is not as trivial as it first seems. Cells can have embedded commas, and even new line characters. The following is one implementation of a CSV reader which can optionally be run asynchronously as a background worker. This implementation returns a standard DataTable which can easily be bound to a DataGridView:
grid.DataSource = dataTable;
The CsvReader class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
namespace CsvReaderExample
{
public class CsvReader
: BackgroundWorker
{
string[] m_lines;
public DataTable DataTable { get; private set; }
public CsvReader(string[] lines)
{
m_lines = lines;
WorkerReportsProgress = true;
WorkerSupportsCancellation = true;
}
public DataTable RunWorker()
{
return DataTable = ParseCsvLines();
}
protected override void OnDoWork(DoWorkEventArgs e)
{
base.OnDoWork(e);
e.Result = DataTable = ParseCsvLines();
}
private DataTable ParseCsvLines()
{
if (m_lines.Length == 0)
return null;
var table = new DataTable();
var columns = table.Columns;
var columnNames = GetRowValues(m_lines[0]);
foreach (var columnName in columnNames)
{
var name = columnName;
int number = 2;
while (columns.Contains(name))
name += " " + number++;
columns.Add(name);
}
var rows = table.Rows;
for (int index = 1, linesCount = m_lines.Length; index < linesCount; index++)
{
if (CancellationPending)
return null;
var line = m_lines[index];
var values = GetRowValues(line);
int valueCount = values.Count;
if (valueCount > columns.Count)
{
int columnNumber = columns.Count;
while (columns.Contains(columnNumber.ToString()))
columnNumber++;
columns.Add(columnNumber.ToString());
}
rows.Add(values.ToArray());
if (WorkerReportsProgress)
ReportProgress(100 * index / linesCount);
}
return table;
}
const char COMMA = ',',
DOUBLE_QUOTE = '"',
VERTICAL_BAR = '|';
private List<string> GetRowValues(string line)
{
var builder = new StringBuilder();
var values = new List<string>();
var inDoubleQuotes = false;
var maxIndex = line.Length - 1;
for (int index = 0; index <= maxIndex; index++)
{
char c = line[index];
if (c == DOUBLE_QUOTE)
{
if (index == 0)
{
inDoubleQuotes = true;
continue;
}
if (index < maxIndex)
{
var nextIndex = index + 1;
if (nextIndex < maxIndex)
{
if (line[nextIndex] == DOUBLE_QUOTE)
{
index++;
if (inDoubleQuotes)
builder.Append(DOUBLE_QUOTE);
continue;
}
}
}
inDoubleQuotes = !inDoubleQuotes;
continue;
}
if (c == COMMA)
{
if (inDoubleQuotes)
{
builder.Append(c);
continue;
}
values.Add(builder.ToString());
builder = new StringBuilder();
continue;
}
builder.Append(c);
}
values.Add(builder.ToString());
return values;
}
#region Sanitise cells with new line characters
public static void SanitiseCellsWithNewLineCharacters(string fileName)
{
var text = File.ReadAllText(fileName, Encoding.Default);
text = text.Replace("\r\n", "\n");
text = text.Replace("\r", "\n");
using (var writer = File.CreateText(fileName))
{
var inDoubleQuotes = false;
foreach (char c in text)
{
if (c == '\n' && inDoubleQuotes)
{
writer.Write(VERTICAL_BAR);
continue;
}
if (c == DOUBLE_QUOTE)
{
if (inDoubleQuotes)
inDoubleQuotes = false;
else
inDoubleQuotes = true;
}
writer.Write(c);
}
}
}
#endregion
}
}
You can read the DataTable synchronously as follows:
var lines = File.ReadAllLines("C:\\registros.csv");
var csvReader = new CsvReader(lines);
var dataTable = csvReader.RunWorker();
You could then remove row(s) from the DataTable with a method such as:
private static void RemoveById(DataTable dataTable, int id)
{
var column = dataTable.Columns["ID"];
if (column == null)
return;
var rows = dataTable.Rows;
for (int index = rows.Count - 1; index >= 0; index--)
{
var row = rows[index];
var value = row ["ID"];
if (value == null)
continue;
if (value.Equals(id))
{
rows.RemoveAt(index);
return;
}
}
}
Call it:
RemoveById(dataTable, 1);
The first thing that is wrong with your implementation is that you use ',' as the separator. You should either split on the new-line character '\n' or read the file line by line as follows:
var lines = new List<string>();
var file = new System.IO.StreamReader("c:\\registros.csv");
string line;
while((line = file.ReadLine()) != null)
{
lines.Add(line);
}
file.Close();
You could then look for the line that starts with the id you are looking for. When you find it, remove the line from the list.
for(int i=0; i++; i<lines.Count)
{
if (lines[i].StartsWith(searchid))
{
lines.RemoveAt(i);
break;
}
}
Next step is to write the result back to the file:
File.WriteAllLines("c:\\registros.csv", lines);
Regarding your second question, I found a similar Q/A on stackoverflow here.
First step is creating the DataTable, then you'll have to bind the table to the table control that will show the data.
SIMPLE & UNDERSTANDABLE!`
Solution For your First Problem is:
****Reading & Writing back to CSV File!****
string searchid = "1";
string[] values = File.ReadAllText(#"Complete Path Of File").Split(new char[] { '\n' });
StringBuilder ObjStringBuilder = new StringBuilder();
for (int i = 0; i < values.Length - 1; i++)
{
if (values[i].StartsWith(searchid) == false)
{
ObjStringBuilder.Append(values[i]+"\n");
}
}
File.WriteAllText(#"Complete Path Of File", ObjStringBuilder.ToString());
}
Answer to your Second Doubt:
****Populating DataGridView dynamically from CSV File!****
Comma(,) Problem SOLVED:
DataTable dtDataSource = new DataTable();
string[] fileContent = File.ReadAllLines(#"..\\Book1.csv");
if (fileContent.Count() > 0)
{
//Create data table columns dynamically
string[] columns = fileContent[0].Split(',');
for (int i = 0; i < columns.Count(); i++)
{
dtDataSource.Columns.Add(columns[i]);
}
//Add row data dynamically
for (int i = 1; i < fileContent.Count(); i++)
{
string[] rowData = fileContent[i].Split(',');
string[] realRowData = new string[columns.Count()];
StringBuilder collaboration = new StringBuilder();
int v = 0;
//this region solves the problem of a cell containing ",".
#region CommaSepProblem
for (int j = 0, K = 0; j < rowData.Count(); j++, K++)
{
//After splitting the line with commas. The cells containing commas will also be splitted.
//Fact: if a cell contains special symbol in excel that cell will be saved in .csv contained in quotes E.g A+B will be saved "A+B" or A,B will be saved as "A,B"
//Our code splits everything where comma is found. So solution is:
//Logic: After splitting if a string contains even number of DoubleQuote then its perfect cell otherwise, it is splitted in multiple cells of array.
if ((rowData[j].Count(x => x == '"') % 2 == 0))//checks if the string contains even number of DoubleQuotes
{
realRowData[K] = quotesLogic((rowData[j]));
}
else if ((rowData[j].Count(x => x == '"') % 2 != 0))//If Number of DoubleQuotes are ODD
{
int c = rowData[j].Count(x => x == '"');
v = j;
while (c % 2 != 0)//Go through all the next array cell till it makes EVEN Number of DoubleQuotes.
{
collaboration.Append(rowData[j] + ",");
j++;
c += rowData[j].Count(x => x == '"');
}
collaboration.Append(rowData[j]);
realRowData[K] = quotesLogic(collaboration.ToString());
}
else { continue; }
}
#endregion
dtDataSource.Rows.Add(realRowData);
}
if (dtDataSource != null)
{
dataGrid1.ItemsSource = dtDataSource.DefaultView;
}
}
Add This Method Too:
string quotesLogic(string collaboration)
{
StringBuilder after = new StringBuilder(collaboration);
if (after.ToString().StartsWith("\"") && after.ToString().EndsWith("\""))//removes 1st and last quotes as those are system generated
{
after.Remove(0, 1);
after.Remove(after.Length - 1, 1);
int count = after.Length - 1;
//FACT: if you try to add DoubleQuote in a cell in excel. It'll save that quote as 2 times DoubleQuote(Like "") which means first DoubleQuote is to give instruction to CPU that the next DoubleQuote is not system generated.
while (count > 0)//This loop find twice insertion of 2 DoubleQuotes and neutralise them to One DoubleQuote.
{
if (after[count] == '"' && after[count - 1] == '"')
{
after.Remove(count, 1);
}
count--;
}
}
return after.ToString();
}

Opening a file and using the string within

When I open a file (I made myself) I need to use somethings out of the string of text that comes trough. I want to use some parts of the text as coordinates to draw a graph with.
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
char XgetalEen;
char XgetalTwee;
char YgetalEen;
char Ygetaltwee;
string XgetalSamen = "";
string YgetalSamen = "";
int coordinaatX;
int coordinaatY;
DialogResult lel = MessageBox.Show("Do you want to close this file?", "OPEN", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (lel == DialogResult.Yes)
{
Open();
foreach(string s in Gcowde)
{
XgetalEen = s[5];
XgetalTwee = s[6];
YgetalEen = s[8];
Ygetaltwee = s[9];
XgetalSamen += XgetalEen + XgetalTwee;
YgetalSamen += YgetalEen + Ygetaltwee;
if(XgetalTwee==' ')
{
XgetalSamen = "";
XgetalTwee = '0';
XgetalSamen += XgetalTwee + XgetalEen;
YgetalEen = s[7];
Ygetaltwee = s[8];
YgetalSamen = "";
YgetalSamen += YgetalEen + Ygetaltwee;
}
if(Ygetaltwee==' ')
{
Ygetaltwee = '0';
YgetalSamen = "";
YgetalSamen += Ygetaltwee + YgetalEen;
}
MessageBox.Show(XgetalSamen + " " + YgetalSamen);
Int32.TryParse(XgetalSamen, out coordinaatX);
Int32.TryParse(YgetalSamen, out coordinaatY);
currentLocation.X += coordinaatX;
currentLocation.Y += coordinaatY;
Coord.Add(new Point(currentLocation.X, currentLocation.Y));
}
drawerryting();
}
}
public void Open()
{
Gcowde.Clear();
listBox1.Items.Clear();
Coord.Clear();
werkVlak.Clear(Color.Black);
Coord.Add(new Point(pictureBox1.Width / 2, pictureBox1.Height / 2));
drawerryting();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFileDialog1.FileName);
string errything = sr.ReadToEnd();
string charAdded = "";
foreach (char s in errything)
{
if (s == '\n')
{
Gcowde.Add(charAdded);
charAdded = "";
}
else
{
charAdded += s;
}
}
foreach (string s in Gcowde)
{
listBox1.Items.Add(s);
}
sr.Close();
}
This is the code how I open the file and get the coordinates out of the string. The string is of this kind L1 G2 X50 Y50. i need to get the 2 50s out of the string.
ps.: the variables are in dutch.
XgetalEen = XnumberOne, XgetalTwee=XnumberTwo,
same goes for Y.
XgetalSamen=XnumberTogether, YgetalSamen=YnumberTogether.
This is a simple example how you could parse the file:
// Read your file using File.ReadAllLines
String[] lines = new[] { "L1 G2 X50 Y50", "L1 G2 X50 Y50" };
foreach (var line in lines)
{
String[] values = line.Split(' ');
string x = values.Where(s => s.StartsWith("X")).First().Replace("X", String.Empty);
int xCoordinate = Convert.ToInt32(x);
}
Don't forget to add all necessary checks and reading of other variables.

remove space at the end of the line in text file

I have got text file with the contents like the below
wYFgemq4-IU372t5I-J0UIIdAd-gcojGR7z BA1111111
HoSOtYLI-90yntvqB-2rV/RLiG-BT69R0NV BA1111111
h1uLXWq4-IU2QUkVr-UYuqipiT-byAuoHn7 BG2222222
jL2MFmq4-IU1VLifN-LZmFc+bu-ibc/2IJp GC1111111
zhoZpmq4-IU27lkQ1-kqNLXTbT-ec28qGPR FG1111111
but unfortunately there is one more space is adding at the end of 5th line by this I am getting an error when I upload the file ...
How can I remove the space ant the end of the fifth line (i.e)
zhoZpmq4-IU27lkQ1-kqNLXTbT-ec28qGPR FG1111111(at here)
would any one please help on this
and this is my code
private bool ParseUploadedDoc(string strUpload)
{
bool blresult = true;
strUpload = strUpload.Replace("\r","");
char [] delimitedchars = {'\n'};
string[] splitwords = strUpload.Split(delimitedchars);
string[] column;
StringBuilder InvalidCert = new StringBuilder();
StringBuilder InvalidSerial = new StringBuilder();
foreach (string word in splitwords)
{
column = word.Split('\t');
column[1].Trim();
if (column[0].Length != 35)
{
InvalidCert.Append(column[0].ToString());
InvalidCert.Append(", ");
blresult = false;
}
/// getting error at here
if (column[1].Length != 9)
{
InvalidSerial.Append(column[1].ToString());
InvalidSerial.Append(", ");
blresult = false;
}
}
if (blresult == false)
{
string strErrCert = "Invalid Certificate Id(s): " + InvalidCert.ToString();
strErrCert = strErrCert.Substring(0, strErrCert.Length - 2);
LblInvalidCert.Text = strErrCert;
string strErrFru = "Invalid Serial Number(s): " + InvalidSerial.ToString();
strErrFru = strErrFru.Substring(0, strErrFru.Length - 2);
LblInvalidFru.Text = strErrFru;
}
return blresult;
}
Problem is at this line
column[1].Trim();
you should do
column[1] = column[1].Trim();

C# Wont save to database after 2nd Click

So my program works as it should. When I click the save button everything is saved to the database. However when I click the save button a second time it fails to work.Index was outside the bounds of the array. is the error in private void btnTest_click on line string Ullage = splitstring[2];
private void btnSave_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\2014-06-26 TEK687 Config Tool\TEK687 Config Tool\bin\Debug\Results.mdb");
string SqlString = "insert into Table1 (PassOrFail,DateTested,TekNum,BatchNum,WeekNum,Serial,FirmwareVer,HardwareVer,TestPC,SettingsTest,Deleted,Ullage,SRC,Vbatt,Tamb,Ullage2,SRC2,Vbatt2,Tamb2) Values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("PassOrFail", txtPassFail.Text);
cmd.Parameters.AddWithValue("DateTested", txtDateTested.Text);
cmd.Parameters.AddWithValue("TekNum", txtTekPartNo.Text);
cmd.Parameters.AddWithValue("BatchNum", txtBatchNumber.Text);
cmd.Parameters.AddWithValue("WeekNum", txtWeekYearNo.Text);
cmd.Parameters.AddWithValue("Serial", txtSerialNumber.Text);
cmd.Parameters.AddWithValue("FirmwareVer", txtFirmwareVer.Text);
cmd.Parameters.AddWithValue("HardwareVer", txtHardwareVer.Text);
cmd.Parameters.AddWithValue("TestPC", txtTestPC.Text);
cmd.Parameters.AddWithValue("SettingsTest", cboSettingsProfiles.SelectedIndex);
cmd.Parameters.AddWithValue("Deleted", txtDeleted.Text);
cmd.Parameters.AddWithValue("Ullage", txtUllage1.Text);
cmd.Parameters.AddWithValue("SRC", txtSRC1.Text);
cmd.Parameters.AddWithValue("Vbatt", txtVbatt1.Text);
cmd.Parameters.AddWithValue("Tamb", txtTamb1.Text);
cmd.Parameters.AddWithValue("Ullage2", txtUllage2.Text);
cmd.Parameters.AddWithValue("SRC2", txtSRC2.Text);
cmd.Parameters.AddWithValue("Vbatt2", txtVbatt2.Text);
cmd.Parameters.AddWithValue("Tamb2", txtTamb2.Text);
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data stored successfully");
}
ClearTextBoxes(this);
}
Here is the code to add values to database error is at string Ullage = splitstring[2];
private void btnTest_Click(object sender, EventArgs e)
{
Cancel = false;
if (DiscoverDevice(false) == false)
{
MessageBox.Show("Error, device is not responding");
return;
}
string servo = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,S," + txtToolID.Text + ",30,\r\n", "\r\n", 4, ref servo, 500);
string test = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,T," + txtToolID.Text + "\r\n", "\r\n", 4, ref test, 500);
string[] splitstring = test.Split(',');
**string Ullage = splitstring[2];**
string SRC = splitstring[3];
string RSSI = splitstring[4];
string AlarmStatus = splitstring[5];
string RateofChange = splitstring[6];
string Tamb = splitstring[7];
string Vbatt = splitstring[8];
Ullage = Ullage.Replace("u:", "");
Tamb = Tamb.Replace("t:", "");
Vbatt = Vbatt.Replace("v:", "");
int Ull = Convert.ToInt32(Ullage);
int src = Convert.ToInt32(SRC);
int BV = Convert.ToInt32(Vbatt);
int temp = Convert.ToInt32(Tamb);
StringBuilder sb = new StringBuilder();
sb.Append(Ull);
txtUllage1.Text += sb.ToString();
StringBuilder sc = new StringBuilder();
sc.Append(src);
txtSRC1.Text += sc.ToString();
StringBuilder sd = new StringBuilder();
sd.Append(BV);
txtVbatt1.Text += sd.ToString();
StringBuilder se = new StringBuilder();
se.Append(temp);
txtTamb1.Text += se.ToString();
StringBuilder sm = new StringBuilder();
if ((Ull < 11) || (Ull > 13) || (src < 9) || (BV < 29))
{
txtPassFail.Text += "12cm FAIL";
txtResultsReading.Font = new Font(txtResultsReading.Font, FontStyle.Bold);
StringBuilder th = new StringBuilder();
th.Append("12cm FAIL");
txtResultsReading.Text += th.ToString();
}
string servoTwo = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,S," + txtToolID.Text + ",31,\r\n", "\r\n", 4, ref servoTwo, 500);
string tests = "";
MyModemSerialInterfaceLayer.WriteTextAndWaitForResponse("TL,T," + txtToolID.Text + "\r\n", "\r\n", 4, ref tests, 500);
string[] splitstrings = tests.Split(',');
string Ullage2 = splitstrings[2];
string SRC2 = splitstrings[3];
string RSSI2 = splitstrings[4];
string AlarmStatus2 = splitstrings[5];
string RateofChange2 = splitstrings[6];
string Tamb2 = splitstrings[7];
string Vbatt2 = splitstrings[8];
Ullage2 = Ullage2.Replace("u:", "");
Tamb2 = Tamb2.Replace("t:", "");
Vbatt2 = Vbatt2.Replace("v:", "");
int Ull2 = Convert.ToInt32(Ullage2);
int src2 = Convert.ToInt32(SRC2);
int BV2 = Convert.ToInt32(Vbatt2);
int temp2 = Convert.ToInt32(Tamb2);
StringBuilder sf = new StringBuilder();
sf.Append(Ull2);
txtUllage2.Text += sf.ToString();
StringBuilder sg = new StringBuilder();
sg.Append(src2);
txtSRC2.Text += sg.ToString();
StringBuilder sh = new StringBuilder();
sh.Append(BV2);
txtVbatt2.Text += sh.ToString();
StringBuilder si = new StringBuilder();
si.Append(temp2);
txtTamb2.Text += si.ToString();
txtDateTested.Text = DateTime.Now.ToString();
txtTestPC.Text = System.Environment.UserName;
//boSettingsProfiles.Text= Settings.SettingsFile;
txtDeleted.Text = "CURRENT";
if ((Ull < 11) || (Ull > 13) || (src < 9) || (BV < 29))
{
txtPassFail.Text += " 3M FAIL";
txtResultsReading.Font = new Font(txtResultsReading.Font, FontStyle.Bold);
StringBuilder tg = new StringBuilder();
tg.Append(Environment.NewLine);
tg.Append("3M FAIL");
txtResultsReading.Text += tg.ToString();
}
else if ((Ull >= 11) && (Ull <= 13) && (src == 9) && (BV >= 29) &&
(Ull2 >= 11) && (Ull2 <= 13) && (src2 == 9) && (BV2 >= 29))
{
txtPassFail.Text += "PASS";
txtResultsReading.Font = new Font(txtResultsReading.Font, FontStyle.Bold);
txtResultsReading.Text += "PASS";
}
ReleaseDevice();//release the config tool after config is completed
}
}
Your splitstrings object doesn't have three objects in it, therefore you can't access the object at index 2. Therefore, you should implement a check to make sure it contains an object at that index before accessing, then handle the case where it doesn't as appropriate.
By the way, next time you ask a question about why something doesn't work, it's absolutely critical that you tell us about the exception you're getting, rather than making us ask for it. And you need to include the code that throws the exception. See How to create a Minimal, Complete, and Verifiable example.
Inspect the variable coming out of the WriteTextAndWaitForResponse call. It probably doesn't have 3 commas.

Read lines at different indexes

Here is some code i put together to search for numbers in a text file. It work's great for what i'm trying to do. right now it finds 7 locations and i need to read the lines at the 7 different indexes. what might be the best way to start this. Thanks, this is in C#.
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = "";
using (OpenFileDialog dlgOpen = new OpenFileDialog())
{
//long count = 0; string line;
//bool start = false;
//string line;
List<String> LinesFound = new List<string>();
// Available file extensions
dlgOpen.Filter = "All files(*.*)|*.*";
// Initial directory
dlgOpen.InitialDirectory = "C://bin";
// OpenFileDialog title
dlgOpen.Title = "Load";
// Show OpenFileDialog box
if (dlgOpen.ShowDialog() == DialogResult.OK)
textBox1.Text = dlgOpen.FileName;
{
string str = System.IO.File.ReadAllText(dlgOpen.FileName);
Regex reg = new Regex("333333");
Match sat = reg.Match(str);
while (sat.Success)
{
richTextBox1.Text += (sat.Index + " "); //shows index where 333333 is
sat = reg.Match(str, sat.Index + sat.Length);
{
{
}
}
}
}
}
}
You can use ReadAllLines instead of ReadAllText, and match each line one by one, use a int[] variable to store all your matching line index.
var lines = File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "/files/file.txt");
Regex reg = new Regex("333333");
string str;
for(int i =1; i<lines.Length;i++)
{
str = lines[i];
Match sat = reg.Match(str);
if (sat.Success)
{
richTextBox1.Text += (i + 1 +" "); //shows index where 333333 is
}
}

Categories

Resources