So, I need to look through the file and fill and 2d array with data from the file. I couldn't figure any better way to do that than this, but this code just completly freezes. Here's the code.
The idea is that I'm gonna look through all of the text in a source file, then I'm gonna check if a line contains something I need and, if so, I will make additions to my 2D array, that I will then write to a different txt file.
string[,] FileBase = new string[100,100];
DateTime Date = DateTime.UtcNow;
string time = Date.ToString();
time = time.Replace(':', '.');
string ReportPath = Directory.GetCurrentDirectory() + "\\Report from " + time + ".txt";
int Value = 0;
int i = 0, j = 0;
string item;
int controlD = 0;
int sensor = 0;
int p = 0;
bool loadcell = false;
bool possensor = false;
int smth = 0;
string curr = comboBox1.SelectedItem.ToString();
curr = curr.Remove(0, curr.IndexOf("RCU") + 3);
int current = Convert.ToInt32(curr);
string localpath = path + "\\control\\RCU" + curr + "\\cfg\\RCU" + curr + ".cfg";
FileStream file1 = new FileStream(localpath, FileMode.Open);
StreamReader reader = new StreamReader(file1);
while ((item = reader.ReadLine()) != null)
{
for (i = p; i < 100; i++)
{
for (j = 0; j < 1000; i++)
{
if (item.Contains("Signal_Sensor"))
{
sensor++;
FileBase[i, j] = "Signal_SensorA" + sensor;
break;
}
else if (item.Contains("Signal_PositionA"))
{
controlD++;
FileBase[i, j] = "Signal_PositionA" + controlD;
break;
}
else if (item.Contains("Division") && (controlD != 0))
{
FileBase[i, j] = "Division";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("LowerLimitExternal"))
{
FileBase[i, j] = "LowerLimitExternal";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("UpperLimitExternal"))
{
FileBase[i, j] = "UpperLimitExternal";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("LowerLimit"))
{
FileBase[i, j] = "LowerLimit";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("UpperLimit"))
{
FileBase[i, j] = "UpperLimit";
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("LoadCell"))
{
loadcell = true;
break;
}
else if (item.Contains("PositionSensor"))
{
possensor = true;
break;
}
else if (item.Contains("EnableSensorA" + smth))
{
smth++;
FileBase[i, j] = "EnableSensorA" + smth;
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
else if (item.Contains("InvertSensorA"))
{
smth++;
FileBase[i, j] = "InvertSensorA" + (smth - 3);
FileBase[i, j + 1] = Convert.ToString(CommaClear(Value));
break;
}
if (smth ==6)
{
smth = 0;
break;
}
}
p = i;
break;
}
}
reader.Close();
File.Create(ReportPath);
FileStream ReportFill = new FileStream(ReportPath, FileMode.Open);
StreamReader reader1 = new StreamReader(ReportFill);
WriteArray();
reader1.Close();
Thanks in advance!
Related
Here's my code.
CustomClass.cs
class ScoreBoard(){
private int m_lastCnt;
public ScoreBoard{
m_lastCnt = 0;
}
public void makeBoard(string history) {
string[] arrPartStr = history.Split(',');
int[] arrPart = new int[arrPartStr.Length];
for (int c = 0; c < arrPart.Length; c++)
{
int temp = 0;
if (arrPartStr[c][0] == 'P') temp = 100;
else if (arrPartStr[c][0] == 'B') temp = 200;
else temp = 300;
if (arrPartStr[c][1] == 'P') temp += 10;
if (arrPartStr[c][2] == 'P') temp += 1;
arrPart[c] = temp;
}
//var strTmp : String = strData;
//strTmp = "311|101|211|211|211|211|211|211|211|211|111|111|111|111|111|111|111|111|111"
//strTmp = strData.replace(/:/g,"");
int[,] arrTmp = new int[6100, 104];
}
}
Main Class i call the void method like this
ScoreBoard sb = ScoreBoard();
string history = "s ,o ,m ,e ,s ,t ,r ,i ,n ,g";
private void Start(){
sb.makeBoard(history);
}
How can i print my 2D array in my console?
I tried doing it like the for(int row){for(int col){}} but its not working i don't know why
Do you mean this?
for (int j = 0; j < arrTmp.GetLength(1); j++)
{
for (int i = 0; i < arrTmp.GetLength(0); i++)
{
var msg = "[" + i.ToString() + ", " + j.ToString() + "] = " + arrTmp[i, j].ToString();
Debug.Log(msg);
}
}
I got it to display:)
CustomClass.cs
int[,] arrTmp = new int[104, 6];
public int[,] GetBoard(){ return arrTmp }
MainClass.cs
int[,] arrayBigRoad = bsb.GetBoard();
for (int j = 0; j < arrTmp.GetLength(1); j++)
{
for (int i = 0; i < arrTmp.GetLength(0); i++)
{
var msg = "[" + i.ToString() + ", " + j.ToString() + "] = " + arrTmp[i, j].ToString();
Debug.Log(msg);
}
}
Thanks though Rodrigo . I'll mark yours as an answer
Im making an app that will use one Excel document that is generated, and place some values from that document to another Excel document, and Im stuck in phase where I need to copy value.
My code:
private void buttonIzvrsi_Click(object sender, EventArgs e)
{
if(textBoxPolazna.Text!="" && textBoxKrajnja.Text != "")
{
Microsoft.Office.Interop.Excel.Application polazniExcel = new Microsoft.Office.Interop.Excel.Application();
polazniExcel.FileValidation = MsoFileValidationMode.msoFileValidationSkip;
Microsoft.Office.Interop.Excel.Workbook polazna = polazniExcel.Workbooks.Open(textBoxPolazna.Text.ToString());
Excel.Worksheet Polazni = polazniExcel.Sheets[1];//sheet koji treba unijeti
Microsoft.Office.Interop.Excel.Application krajnjiExcel = new Microsoft.Office.Interop.Excel.Application();
krajnjiExcel.FileValidation = MsoFileValidationMode.msoFileValidationSkip;
Microsoft.Office.Interop.Excel.Workbook krajnja = krajnjiExcel.Workbooks.Open(textBoxKrajnja.Text.ToString());
Excel.Worksheet Krajnji_PoMT = krajnjiExcel.Sheets["Po mjestu troška"];//sheet po mjestu troska
Excel.Worksheet Krajnji_Ukupno = krajnjiExcel.Sheets["Ukupno po mjesecima"];//sheet ukupno
Excel.Range brojRedovaPolazni = Polazni.UsedRange;
int brojacRedovaPolazni = brojRedovaPolazni.Rows.Count; //broj redova u polaznom excelu
Excel.Range brojRedovaKrajnjiMT = Krajnji_PoMT.UsedRange;
int brojacRedovaKrajnjiMT = brojRedovaKrajnjiMT.Rows.Count;//broj redova u krajnjem excelu sheet mjesto troska
Excel.Range brojRedovaKrajnjiUkupno = Krajnji_Ukupno.UsedRange;
int brojacRedovaKrajnjiUkupno = brojRedovaKrajnjiUkupno.Rows.Count;//broj redova u krajnjem excelu sheet ukupno
List<string> listaMT = new List<string>();
List<string> PostojeciMjeseci = new List<string>(); //tu planiram trpati mjesece koji postoje
if (brojacRedovaPolazni == brojacRedovaKrajnjiMT)
{
for (int i = 1; i <= 12; i++)
{
if(Polazni.Cells[9, i + 2].Value != null || Polazni.Cells[9, i + 2].Value != "")
{
listaMT.Add(Polazni.Cells[9, i + 2].Value);
}
}
PostojeciMjeseci = mjeseci.Intersect(listaMT).ToList(); //ovi mjeseci postoje
int kolumna = 0;
for (int i = 0; i < PostojeciMjeseci.Count; i++)
{
for (int j = 1; j < 12; j++)
{
//MessageBox.Show(Polazni.Cells[9, j + 2].Value);
if (string.Equals(PostojeciMjeseci[i], Polazni.Cells[9, j + 2].Value))
{
#region Broj kolumne
if (string.Equals(Polazni.Cells[9, j + 2].Value, "siječanj")) kolumna = 3;//"C";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "veljača")) kolumna = 4;// "D";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "ožujak")) kolumna = 5;// "E";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "travanj")) kolumna = 6;// "F";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "svibanj")) kolumna = 7;// "G";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "lipanj")) kolumna = 8;// "H";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "srpanj")) kolumna = 9;// "I";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "kolovor")) kolumna = 10;// "J";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "rujan")) kolumna = 11;// "K";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "listopad")) kolumna = 12;// "L";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "studeni")) kolumna = 13;// "M";
else if (string.Equals(Convert.ToString(Polazni.Cells[9, j + 2].Value), "prosinac")) kolumna = 14;// "N";
#endregion
//MessageBox.Show("U petlji: "+Polazni.Cells[9, j + 2].Value);
string sValue = "";
for (int x = 1; x <= brojacRedovaKrajnjiMT - 12; x++)
{
Krajnji_PoMT.Cells[(x + 12), kolumna].Value = Polazni.Cells[(x + 12), kolumna].Value;
}
}
}
}
}
else if (brojacRedovaPolazni == brojacRedovaKrajnjiUkupno)
{
for (int i = 1; i <= brojacRedovaKrajnjiUkupno; i++)
{
}
}
else
{
MessageBox.Show("Broj redova nije konzistentan s glavnom tablicom.");
}
polazna.Close(true, Type.Missing, Type.Missing);
krajnja.Close(true, Type.Missing, Type.Missing);
polazniExcel.Quit();
krajnjiExcel.Quit();
}
else
{
MessageBox.Show("Unesite obe putanje do Excel datoteka.");
}
}
My problem is in the line:
Krajnji_PoMT.Cells[(x + 12), kolumna].Value = Polazni.Cells[(x + 12), kolumna].Value;
I tried many variations but I can never get that value pasted to another Excel. If I say:
Krajnji_PoMT.Cells[(x + 12), kolumna].Value = "test";
then it works. Whats the catch here?
I need a help with iText in C#. I'm trying to extract a table from a PDF file and save this into a new CSV file, keeping the values in the correct places. For this, I thought the solution was to create a two-dimensional array to organize the data.
Extracting all information from PDF with iText, I saw it was possible to get some numerical data that seemed to be the position of a piece of text on the page and I organized my array based these indexes. It didn’t work, the text was completely dispersed in various different cells. Now, I want to know what this values means, because they don't follow a "correct" order and I want to know if is possible to organize the future table with this.
I'm using ";" as delimiter cell.
For testing, I'm using this PDF
http://www.americana.sp.gov.br/americanaV5/download/contasPublicas/Despesa_Categoria_Economica_2014.pdf
Here's my code:
protected void Button2_Click(object sender, EventArgs e)
{
try
{
TextBox2.Text = "";
byte[] conteudo = download(TextBox1.Text);
if (conteudo != null)
{
PdfReader leitorp = new PdfReader(conteudo);
ITextExtractionStrategy estrategia = new SimpleTextExtractionStrategy();
List<Celula> celulas = new List<Celula>();
int i, j;
for (i = 1; i <= leitorp.NumberOfPages; i++)
{
//Total and crude extraction of all information from text in PDF via iText, separate lines in an array of strings.
string[] linhas = (Encoding.UTF8.GetString(Encoding.Convert(Encoding.Default, Encoding.UTF8, leitorp.GetPageContent(i)))).Split('\n');
for (j = 1; j < linhas.Length; j++)
{
if (linhas[j].Length > 2)
{
if (linhas[j].Substring(0, 2).Equals("BT"))
{
string[] campos = linhas[j].Split(' ');
Celula umacelula = new Celula();
umacelula.coluna = float.Parse(campos[1]);
umacelula.linha = float.Parse(campos[2]);
linhadodebug = j;
int t1 = linhas[j].IndexOf('(');
int t2 = linhas[j].LastIndexOf(')');
umacelula.conteudo = System.Text.RegularExpressions.Regex.Replace((linhas[j].Substring(linhas[j].IndexOf('(') + 1, (linhas[j].LastIndexOf(')') - 1 - linhas[j].IndexOf('(')))), #"\s\s+", "");
celulas.Add(umacelula);
}
}
}
}
leitorp.Close();
string[] totallinhas = new string[celulas.Count];
string[] totalcolunas = new string[celulas.Count];
for (i = 0; i < celulas.Count; i++)
{
totallinhas[i] = celulas[i].linha.ToString();
totalcolunas[i] = celulas[i].coluna.ToString();
}
totallinhas = totallinhas.Distinct().ToArray();
totalcolunas = totalcolunas.Distinct().ToArray();
Array.Sort(totallinhas);
Array.Reverse(totallinhas);
Array.Sort(totalcolunas);
Array.Reverse(totalcolunas);
string[,] matriz = new string[totallinhas.Length + 1, totalcolunas.Length + 1];
for (i = 1; i < totallinhas.Length; i++)
{
matriz[i, 0] = totallinhas[i - 1].ToString();
}
for (i = 1; i < totalcolunas.Length; i++)
{
matriz[0, i] = totalcolunas[i - 1].ToString();
}
int z;
for (i = 0; i < celulas.Count(); i++)
{
for (j = 1; j < matriz.GetLength(0); j++)
{
for (z = 1; z < matriz.GetLength(1); z++)
{
if ((celulas[i].linha.ToString().Equals(matriz[j, 0])) && (celulas[i].coluna.ToString().Equals(matriz[0, z])))
{
matriz[j, z] = celulas[i].conteudo.ToString();
}
}
}
}
StringWriter texto = new StringWriter();
for (i = 0; i < matriz.GetLength(0); i++)
{
for (j = 0; j < matriz.GetLength(1); j++)
{
texto.Write(matriz[i, j] + ";");
}
texto.WriteLine();
}
Response.ContentType = "text/plain";
Response.AddHeader("content-disposition", "attachment;filename=" + string.Format("teste-{0}.csv", string.Format("{0:ddMMyyyy}", DateTime.Today)));
Response.Clear();
using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.UTF8))
{
writer.Write(texto.ToString());
}
Response.End();
}
}
catch (Exception E)
{
TextBox2.Text = "Erro Button2_Click: " + E.Message + " # " + linhadodebug.ToString();
}
}
And here, the struct of celula (cell) and method to download the file:
public struct Celula
{
public float coluna;
public float linha;
public string conteudo;
public Celula(float coluna, float linha, string conteudo)
{
this.coluna = coluna;
this.linha = linha;
this.conteudo = conteudo;
}
public Celula(Celula celula)
{
this.coluna = celula.coluna;
this.linha = celula.linha;
this.conteudo = celula.conteudo;
}
}
protected byte[] download(string url)
{
try
{
WebRequest endereco = HttpWebRequest.Create(url);
Stream leitor = endereco.GetResponse().GetResponseStream();
MemoryStream memoria = new MemoryStream();
byte[] conteudo = null;
int count = 0;
do
{
byte[] buffer = new byte[1024];
count = leitor.Read(buffer, 0, 1024);
memoria.Write(buffer, 0, count);
}
while (leitor.CanRead && count > 0);
// Converte da memória direto para bytes
conteudo = memoria.ToArray();
if (conteudo != null)
{
return conteudo;
}
else
{
TextBox2.Text = "Error: download null.";
return null;
}
}
catch (Exception E)
{
TextBox2.Text = "Error download: " + E.Message;
return null;
}
}
This is a non-profit project. I hope you can help me. Thank you!
hi im formulating my question now better.
in the foreach command i get for temp(save variable) values in an array. The values that i save in temp are from the datagridview cells.
in the next step, in the for command, i want to compare 2 strings, the string and the next string, if the fist string is bigger than the second, i want to change their positions. But there is the problem, they dont change positions they even get an empty value, and i cant understand why they get an empty value.
Im thinking that they get an empty value because of the foreach command, the index [i] just stays the same, but if i would put in i = i+1, the command would be out of bound.
Thank you
senc. NIko
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[i].Value == null)
{
//MessageBox.Show("This row is empty");
break;
}
if (row.Cells[i].Value != null)
{
temp = row.Cells[i].Value.ToString();
UnsortArray[i] = temp;
i = i + 1;
}
}
for (int a = 0; a < MaxZeilen; a++)
{
if (i < MaxZeilen)
{
*if (String.Compare(UnsortArray[a], UnsortArray[a + 1]) > 0)
{
UnsortArray[a] = temp;
UnsortArray[a + 1] = temp2;
temp = UnsortArray[a + 1];
temp2 = UnsortArray[a];
}*
}
}
for (int i = 0; i < MaxZeilen; i++)
{
UnsortArray[i] = SortArray[i];
MessageBox.Show(UnsortArray[i]);
}
You're backwards, assigning the array to your temp variables before assigning the temp variables:
UnsortArray[a] = temp;
UnsortArray[a + 1] = temp2;
temp = UnsortArray[a + 1];
temp2 = UnsortArray[a];
Try:
temp = UnsortArray[a + 1];
temp2 = UnsortArray[a];
UnsortArray[a] = temp;
UnsortArray[a + 1] = temp2;
And you've done it again here UnsortArray[i] = SortArray[i];. I think you mean SortArray[i] = UnsortArray[i];
temp = UnsortArray[a + 1];
UnsortArray[a + 1] = UnsortArray[a];
UnsortArray[a] = temp;
instead of
UnsortArray[a] = temp;
UnsortArray[a + 1] = temp2;
temp = UnsortArray[a + 1];
temp2 = UnsortArray[a];
Why using an array and not a List ?
This page tells about sorting lists.
Here is some improvements to your code. You had an error at the top that could cause a infinite loop and just use the Array.Sort method. If you want it to sort differently, add an IComparable interface.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[i].Value == null)
{
//MessageBox.Show("This row is empty");
i++;
break;
}
else (row.Cells[i].Value != null)
{
UnsortArray[i] = row.Cells[i].Value.ToString();
i++;
}
}
Array.Sort(UnsortArray);
SortArray = UnsortArray;
List<String> itemList = new List<string>();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[0].Value = null)
{
itemList.Add(row.Cells[0].Value.ToString());
}
}
itemList.Sort();
string[] SortedArray = itemList.ToArray();
for (int j = 0; j < SortedArray.Length; j++)
{
MessageBox.Show(SortedArray[j]);
}
and if this code doesn't work, than add
foreach(string item in itemList)
{
MessageBox.Show(item);
}
after first foreach loop and check the values
Replace it with the following code block
int i= 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row != null)
{
temp = row.ToString();
UnsortArray[i] = temp;
i = i + 1;
}
}
for (int a = 0; a < MaxZeilen; a++)
{
if (String.Compare(UnsortArray[a], UnsortArray[a + 1]) > 0)
{
temp = UnsortArray[a + 1];
UnsortArray[a + 1] = UnsortArray[a];
UnsortArray[a] = temp;
}
}
for (int i = 0; i < MaxZeilen; i++)
{
MessageBox.Show(UnsortArray[i]);
}
int MaxArrayCount = 0;
foreach(DataGridViewRow row in dataGridView1.Rows)
{
MaxArrayCount += row.Cells.Count;
}
string[] UnsortArray= new string[MaxArrayCount];
int cnt = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
for (int i = 0; i < row.Cells.Count; i++ )
{
if (row.Cells[i].Value != null)
{
temp = row.Cells[i].Value.ToString();
UnsortArray[cnt] = temp;
cnt++;
}
}
}
for (int b = 1; b < UnsortArray.Count; b++)
{
for (int a = 0; a < UnsortArray.Count - 1; a++)
{
if (String.Compare(UnsortArray[a], UnsortArray[a + 1]) > 0)
{
temp = UnsortArray[a + 1];
UnsortArray[a + 1] = UnsortArray[a];
UnsortArray[a] = temp;
}
}
}
for (int i = 0; i < MaxZeilen; i++)
{
MessageBox.Show(UnsortArray[i]);
}
So I've got an array of integer. I want to use a loop and exclude integers that makes the equation true. So that would be like
for (int n = 0; n < first9char.Length; n++ ) {
if (first9char[n] == clickValue) {
first9char[n] = first9char[n + 1];
But then it only changes the value that is equal to not changing whole array. So is there any way to do this?
I want to use it in this loop.
if (UserSquareMethod.clickedBoxes[0] == -1) {
MessageBox.Show("You have not selected any box");
} else {
int i = 0;
do {
if (textButtonArray[clickedBox[i]].Text == "" || clickValue == "") {
textButtonArray[clickedBox[i]].Text = clickValue;
textButtonArray[clickedBox[i]].Font = new Font(textButtonArray[clickedBox[i]].Font.FontFamily, 14, FontStyle.Bold);
}
else
{
textButtonArray[clickedBox[i]].Text += "," + clickValue;
textButtonArray[clickedBox[i]].Font = new Font(textButtonArray[clickedBox[i]].Font.FontFamily, 5, FontStyle.Regular);
string[] first9char = textButtonArray[clickedBox[i]].Text.Split(new string[] { "," }, StringSplitOptions.None);
for (int j = 1; j < first9char.Length; j++)
{
for (int k = j - 1; k >= 0; k--)
{
if (first9char[j] == first9char[k])
{
if (clearNumberClicked == true)
{
first9char = Array.FindAll(first9char, x => x != clickValue);
label2.Text = first9char[0];
//int n = 0;
//for (int p = 0; p < first9char.Length; p++)
//{
// if (first9char[p] != clickValue)
// {
// first9char[n] = first9char[p];
// n++;
// label2.Text += "," + first9char[n];
// }
// }
//for (int n = 0; n < first9char.Length; n++ ) {
//if (first9char[n] == clickValue) {
// first9char[n] = first9char[n + 1];
// for ( int p = 0; p < n; p++) {
//}
//}
//}
MessageBox.Show("Clear the number" + first9char[(first9char.Length - 1)] + "and " + clickValue + " " + first9char.Length);
}
else {
first9char[j] = "";
textButtonArray[clickedBox[i]].Text = first9char[0];
MessageBox.Show("You cannot enter the same number again!"+ first9char[j]+j);
for (int m = 1; m < (first9char.Length - 1); m++) {
textButtonArray[clickedBox[i]].Text += ","+ first9char[m];
}
}
}
}
}
if (textButtonArray[clickedBox[i]].Text.Length > 9)
{
textButtonArray[clickedBox[i]].Text = first9char[0] + "," + first9char[1] + "," + first9char[2] + "," + first9char[3] + "," + first9char[4];
MessageBox.Show("You cannot enter more than 5 numbers, please clear the box if you want to enter different number." + textButtonArray[clickedBox[i]].Text.Length);
}
}
i++;
}
while (clickedBox[i] != -1);
}
}
I would use LINQ for this:
first9char = first9char.Where(x => x != clickValue).ToArray();
It just means "pick the items that don't match". If you can't use LINQ for some reason, then just keep another counter, and make sure to only loop to n from there on in:
int n = 0;
for(int i = 0; i < first9char.Length; i++) {
if(first9char[i] != clickValue) {
first9char[n] = first9char[i];
n++;
}
}
Clean and efficient.