How do I write at a specific index of a line? - c#

Good day Stackoverflow,
I want to write some text at a specific point of a line in a txt-file.
So I want to write something between two ; in the line.
The Line of the textfile is: 20180912_0149;KIV\vischer;12.09.2018;01:49;; .
I want to write it if I click the "Geht" Button. I tried different things with streamreader and writer but I don't get to a solution.
Here is my code of the aspx.cs and my helper class:
Aspx.cs:
namespace Zieterfassung_0._0._2pre_alpha
{
public partial class Zeiten : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sPath = #"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung\obj\Debug\Zeiten.txt";
tb_User.Text = WindowsIdentity.GetCurrent().Name.ToString();
tb_Datum.Text = DateTime.Now.ToString("dd.MM.yyyy");
tb_Zeit.Text = DateTime.Now.ToString("hh:mm");
cZeile KommtDatumZeit = new cZeile();
if (File.Exists(sPath))
{
using (StreamReader sr = new StreamReader(sPath))
{
while (!sr.EndOfStream)
{
KommtDatumZeit = cZeiterfassung.GetZeileObjectFromZeileString(sr.ReadLine(), ";");
}
}
}
tb_Kommt.Text = KommtDatumZeit.dtKommt.ToString();
}
protected void btn_Geht_Click(object sender, EventArgs e)
{
string sAusgabeGeht = string.Format("{0:hh:mm}", tb_Zeit.Text);
string sPath = #"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung\obj\Debug\Zeiten.txt";
FileInfo fi = new FileInfo(sPath);
cZeile Geht = new cZeile();
using (StreamReader sr = new StreamReader(sPath))
{
Geht = cZeiterfassung.GetZeileObjectFromZeileString(sr.ReadLine(), ";");
}
using(StreamWriter sw = new StreamWriter(sPath))
{
}
}
}
}
Helperclass for splitting and array:
namespace Prog
{
public static class cZeiterfassung
{
public static cZeile GetZeileObjectFromZeileString(string Zeile, string Trenner)
{
cZeile ZeileReturn = new cZeile();
string[] separators = { Trenner };
string[] arZeile = Zeile.Split(separators, StringSplitOptions.None);
ZeileReturn.ID = arZeile[0];
if (arZeile[1].IndexOf("\\") != -1)
{
ZeileReturn.Domain = arZeile[1].Substring(0, arZeile[1].IndexOf("\\"));
if (arZeile[1].Length >= arZeile[1].IndexOf("\\"))
ZeileReturn.User = arZeile[1].Substring(arZeile[1].IndexOf("\\") + 1);
}
else
ZeileReturn.User = arZeile[1];
ZeileReturn.Datum = arZeile[2];
ZeileReturn.Kommt = arZeile[3];
ZeileReturn.Geht = arZeile[4];
if(!string.IsNullOrEmpty(arZeile[2]))
ZeileReturn.dtDatum = Convert.ToDateTime(arZeile[2]);
if(!string.IsNullOrEmpty(arZeile[3]))
ZeileReturn.dtKommt = Convert.ToDateTime(arZeile[3]);
if (!string.IsNullOrEmpty(arZeile[4]))
ZeileReturn.dtGeht = Convert.ToDateTime(arZeile[4]);
return ZeileReturn;
}
}//cZeiterfassung
public class cZeile
{
public string ID { get; set; }
public string Domain { get; set; }
public string User { get; set; }
public string Datum { get; set; }
public string Kommt { get; set; }
public string Geht { get; set; }
public DateTime dtDatum { get; set; }
public DateTime dtKommt { get; set; }
public DateTime dtGeht { get; set; }
public string Dauer { get; set; }
}
}

I can't quite Point out what are you trying to do from your code, but from the question you asked:
I would look into every line if you are looking for a specific line
string Data = "";
using(StreamReader Sr = new StreamReader(Path))
{
while(!Sr.EndOfStream())
{
string UseMe = Sr.ReadLine();
Data += UseMe;
}
}
Now you could just validate each line. With the Data-string I gave you a possibility to build each line into one string
I hope I could help you, otherwise contact me directly (I also speak german I guess this is easier for you)

If your file isn't big, I propose you to write to new files with new data.
This is the idea
string[] lines = File.ReadAllLines(sPath);
for (int i = 0; i < lines.Length; i++)
{
if (lines[i].IndexOf(";;") != -1)
{
lines[i] = lines[i].Insert(line.IndexOf(";;"), "xxx");
}
}
File.WriteAllLines(sPathTemp, lines);

Related

Reading CSV file - Object Oriented way

I'd like to parse a csv file in my course that I attend, The cvs file looks like this:
john; 3.5; 32111
etc
I've created a Class for that:
class Student
{
public string name { get; set; }
public double average { get; set; }
public int social_number { get; set; }
public Student(string name, double average, int social_number)
{
this.name = name;
this.average = average;
this.social_number = social_number;
}
public void CSV_digest(string csv_line)
{
if (csv_line != "")
{
string[] chunks = csv_line.Split(';');
name = chunks[0];
average = Convert.ToDouble(chunks[1]);
social_number = Convert.ToInt32(chunks[2]);
}
}
}
I don't really know how to propagate the Student type array:
class Program
{
static void Main(string[] args)
{
StreamReader csv = new StreamReader("students.csv", Encoding.UTF8);
string[] csv_lines = csv.ReadToEnd().Split('\n');
Student[] students = new Student[csv_lines.Length - 1];
for (int i = 0; i < csv_lines.Length; i++)
{
students[i] =
}
Console.ReadKey();
}
}
Could you please help me with this? I'd really like to utilize classes.
There is really no reason to use a library when the code to read CSV is very simple. See my code below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string filename = #"c:\temp\test.csv";
static void Main(string[] args)
{
StreamReader csv = new StreamReader(filename);
string line = "";
List<Student> students = new List<Student>();
while((line = csv.ReadLine()) != null)
{
students.Add(new Student(line));
}
Console.ReadKey();
}
}
class Student
{
public string name { get; set; }
public double average { get; set; }
public int social_number { get; set; }
public Student(string csv_line)
{
if (csv_line != "")
{
string[] chunks = csv_line.Split(';');
name = chunks[0];
average = Convert.ToDouble(chunks[1]);
social_number = Convert.ToInt32(chunks[2]);
}
}
}
}

How do I replace a specific line in a textfile?

Good morning Stackoverflow,
I'm developing a time tracking web application with ASP.Net / C#.
There is a "coming" button that writes in a line of a textfile this: ID;Username;Date;Time.
At the other side, there is the "leaving" button. It should replace the line with the same content but add the time of leaving. So it should be looking like this: ID;Username;Date;TimeOfComing;TimeOfLeaving.
That's the problem. How do I replace the line? Every thing (ID, user etc.) is stored in variables of a helper class named "cZeile". So, how do I replace the line by pushing the "leaving" button aka btn_geht?
Code:
namespace Zieterfassung_0._0._2pre_alpha
{
public partial class Zeiten : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sPath = #"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung`\obj\Debug\Zeiten.txt";`
tb_User.Text = WindowsIdentity.GetCurrent().Name.ToString();
tb_Datum.Text = DateTime.Now.ToString("dd.MM.yyyy");
tb_Zeit.Text = DateTime.Now.ToString("hh:mm");
cZeile KommtDatumZeit = new cZeile();
if (File.Exists(sPath))
{
using (StreamReader sr = new StreamReader(sPath))
{
while (!sr.EndOfStream)
{
KommtDatumZeit = cZeiterfassung.GetZeileObjectFromZeileString(sr.ReadLine(), ";");
}
}
}
tb_Kommt.Text = KommtDatumZeit.dtKommt.ToString();
}
protected void btn_Kommt_Click(object sender, EventArgs e)
{
string ID = DateTime.Now.ToString("yyyyMMdd_hhmm");
string sAusgabeKommt = string.Format("{0:yyyyMMdd_hhmm};{1};{2:dd.MM.yyyy};{3:hh:mm};;", ID, tb_User.Text, tb_Datum.Text, tb_Zeit.Text);
string sPath = #"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung\obj\Debug\Zeiten.txt";
FileInfo fi = new FileInfo(sPath);
if (!fi.Exists)
{
fi.Create().Dispose();
}
using (StreamWriter sw = File.AppendText(sPath))
{
sw.Write(sAusgabeKommt);
}
}
protected void btn_Geht_Click(object sender, EventArgs e)
{
string sAusgabeGeht = string.Format("{0:hh:mm}", tb_Zeit.Text);
string sPath = #"C:\VSTO\Projects\Zeiterfassung\Zeiterfassung\obj\Debug\Zeiten.txt";
FileInfo fi = new FileInfo(sPath);
cZeile Geht = new cZeile();
using (StreamReader sr = new StreamReader(sPath))
{
Geht = cZeiterfassung.GetZeileObjectFromZeileString(sr.ReadLine(), ";");
Geht.Geht = DateTime.Now.ToString("hh:mm");
Geht.dtGeht = DateTime.Now;
using(StreamWriter sw = new StreamWriter(sPath))
{
}
}
}
}
}
Helper Class:
namespace Prog
{
public static class cZeiterfassung
{
public static cZeile GetZeileObjectFromZeileString(string Zeile, string Trenner)
{
cZeile ZeileReturn = new cZeile();
string[] separators = { Trenner };
string[] arZeile = Zeile.Split(separators, StringSplitOptions.None);
ZeileReturn.ID = arZeile[0];
if (arZeile[1].IndexOf("\\") != -1)
{
ZeileReturn.Domain = arZeile[1].Substring(0, arZeile[1].IndexOf("\\"));
if (arZeile[1].Length >= arZeile[1].IndexOf("\\"))
ZeileReturn.User = arZeile[1].Substring(arZeile[1].IndexOf("\\") + 1);
}
else
ZeileReturn.User = arZeile[1];
ZeileReturn.Datum = arZeile[2];
ZeileReturn.Kommt = arZeile[3];
ZeileReturn.Geht = arZeile[4];
if(!string.IsNullOrEmpty(arZeile[2]))
ZeileReturn.dtDatum = Convert.ToDateTime(arZeile[2]);
if(!string.IsNullOrEmpty(arZeile[3]))
ZeileReturn.dtKommt = Convert.ToDateTime(arZeile[3]);
if (!string.IsNullOrEmpty(arZeile[4]))
ZeileReturn.dtGeht = Convert.ToDateTime(arZeile[4]);
return ZeileReturn;
}
}//cZeiterfassung
public class cZeile
{
public string ID { get; set; }
public string Domain { get; set; }
public string User { get; set; }
public string Datum { get; set; }
public string Kommt { get; set; }
public string Geht { get; set; }
public DateTime dtDatum { get; set; }
public DateTime dtKommt { get; set; }
public DateTime dtGeht { get; set; }
public string Dauer { get; set; }
}
}

powershell cmdlet in visual studio 2017, deserialization method

I have got a problem with undestanding powershell cmdlet.
Task is, to deserialize a xml file. I have got a folder with a lot of xml files, I would like to read in an filter certain information using the deserializiation method. My supervisor mentioned that I should use powershell cmdlet... but I haven't heard anything of it before. So what is the benefit? And how do I create such a cmdlet.
That is my code so far:
using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Text;
using System.Management.Automation;
namespace EdocX
{
[Cmdlet(VerbsCommon.Get, "test", SupportsShouldProcess = true)]
public class program : Cmdlet
{
public static string dirPath = #"N:\EGS_SDRE\OB\19_Schnittstellen_eDocX_ITAS\06_Matching EdocX-Objektbrief\01_exemplarische_XMLs_fuer_den_Import\RWA-Anlage"
public static List<string> dirs = new List<string>(Directory.GetFiles(dirPath, "*.xml"));
public static (string[], string[], string[,], string[,], string[,]) deserializeobject(string filename)
{
// Liste Prüfgrundlagen
List<string> pg = new List<string>();
pg.Add("GaVO");
pg.Add("VkVO");
pg.Add("VStättVO");
pg.Add("SPrüfV");
pg.Add("BetrVO");
pg.Add("BbgSGPrüfV");
pg.Add("BremAnlPrüfV");
pg.Add("PVO");
pg.Add("TPrüfVO");
pg.Add("BauPrüfVO M-V");
pg.Add("DVO-NBauO");
pg.Add("PrüfVO NRW");
pg.Add("HTechAnlV RP");
pg.Add("TPrüfVO");
pg.Add("SächsTechPrüfVO");
pg.Add("TAnlVO");
pg.Add("PrüfVO");
pg.Add("ThürTechPrüfVO");
// Auftraggeber - Var
string[] Auftraggeber;
string Name_AG = "";
string Stadt_AG = "";
string PLZ_AG = "";
string Straße_AG = "";
string Hausnummer_AG = "";
string Region_AG = "";
string PARNR_AG = "";
// Aufstellungsort - Var
string[] Aufstellungsort;
string Name_AO = "";
string Stadt_AO = "";
string PLZ_AO = "";
string Straße_AO = "";
string Hausnummer_AO = "";
string Region_AO = "";
string Land_AO = "";
// Anlage - Var
string[,] Anlagen;
string Materialnummer = "";
string EQnummer = "";
string Anlagentyp = "RWA-Anlage";
string[] InterneBezeichnung;
string[] Hersteller;
// Vorgang rückgemeldet - Var
string[,] Vorgang_rückgemeldet;
string Typ_VR = "Prüfung";
string Dienstleister = "TÜV SÜD Industrie Service GmbH";
string Durchführungsdatum = "";
string Maengel = "";
string Bemerkungstexte = "";
string Pruefgrundlage_VR = "";
// Vorgang zukünftig - Var
string[,] Vorgang_zukünftig;
string Typ_VZ = "Prüfung";
string Fälligkeit = "";
string Pruefgrundlage_VZ = "";
//****************************************************************************************************
//********************************************SERIALIZATION*******************************************
// new instance of XMLSerializer --> specifiying type
var serializer = new XmlSerializer(typeof(Document));
// read the XML document
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var encoding = Encoding.GetEncoding("Windows-1252");
using (var sr = new StreamReader(filename, encoding, true))
using (var reader = XmlReader.Create(sr))
{
// restore the object's state using the deserialize method
var i = (Document)serializer.Deserialize(reader);
//---------------------------------------Auftraggeber-----------------------------------------------
int count_Z1ZRMPA = i.IDOC.Z1ZRMDB.Z1ZRMPA.Count;
for (int c = 0; c < count_Z1ZRMPA; c++)
{
if (i.IDOC.Z1ZRMDB.Z1ZRMPA[c].TITLE == "Auftraggeber")
{
Name_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].NAME1 + i.IDOC.Z1ZRMDB.Z1ZRMPA[c].NAME2;
Stadt_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].CITY1;
PLZ_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].POST_CODE1;
Straße_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].STREET;
Hausnummer_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].HOUSE_NUM1;
Region_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].REGION;
PARNR_AG = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].PARNR;
}
//---------------------------------------Aufstellungsort----------------------------------------
if (i.IDOC.Z1ZRMDB.Z1ZRMPA[c].TITLE == "Aufstellungsort")
{
Name_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].NAME1 + i.IDOC.Z1ZRMDB.Z1ZRMPA[c].NAME2;
Stadt_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].CITY1;
PLZ_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].POST_CODE1;
Straße_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].STREET;
Hausnummer_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].HOUSE_NUM1;
Region_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].REGION;
Land_AO = i.IDOC.Z1ZRMDB.Z1ZRMPA[c].COUNTRY;
}
}
//---------------------------------------Anlage----------------------------------------------------
Materialnummer = i.IDOC.Z1ZRMDB.MABEZ;
EQnummer = i.IDOC.Z1ZRMDB.OBJNR;
int count_ANLAGEPRFTXT = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.ANLAGE.PRFTXT.Count;
int AnzahlAnlagen = count_ANLAGEPRFTXT - 1;
InterneBezeichnung = new string[AnzahlAnlagen];
Hersteller = new string[AnzahlAnlagen];
for (int c = 1; c < count_ANLAGEPRFTXT; c++)
{
InterneBezeichnung[c - 1] = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.ANLAGE.PRFTXT[c].ENTRBEREICH;
Hersteller[c - 1] = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.ANLAGE.PRFTXT[c].HERSTELLER;
}
//---------------------------------------Vorgang rückgemeldet-------------------------------------
Durchführungsdatum = i.IDOC.Z1ZRMDB.PRFBER.DATEN.Pruefungszeitraum;
int count_PRFTXT = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT.Count;
for (int c = 0; c < count_PRFTXT; c++)
{
if (i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].KATEGORIE == "Grundlage")
{
string Pruefgrundlage = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].Value;
int count_pg = pg.Count;
for (int cc = 0; cc < count_pg; cc++)
{
if (Pruefgrundlage.Contains(pg[cc]) == true)
{
Pruefgrundlage_VR = pg[cc];
}
}
}
if (i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].ROWTYPE == "Zwischenüberschrift" && i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].PATTERN == "#KATEGORIE[../#KATEGORIE='Mangel' and ../#GEWICHT[not(contains(.,'Beseitigt'))]]")
{
string Maengelabruf = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].Value;
if (Maengelabruf == "Mängel")
{
Maengel = "Mängel_ja";
}
else
{
Maengel = "Mängel_nein";
}
}
if (i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].ROWTYPE == "Mangel" && i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].PATTERN == "#KATEGORIE[../#KATEGORIE='Mangel' and ../#GEWICHT[not(contains(.,'Beseitigt'))]]")
{
string Bemerkungstext = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].Value;
Bemerkungstexte += " " + Bemerkungstext;
}
}
//---------------------------------------Vorgang zukünftig--------------------------------------
int count_Z1ZRMAU = i.IDOC.Z1ZRMDB.Z1ZRMAU.Count;
for (int c = 0; c < count_Z1ZRMAU; c++)
{
if (i.IDOC.Z1ZRMDB.Z1ZRMAU[c].MNAME == "Nächste Wiederkehrende Prüfung")
{
Fälligkeit = i.IDOC.Z1ZRMDB.Z1ZRMAU[c].MWERT;
}
}
for (int c = 0; c < count_PRFTXT; c++)
{
if (i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].KATEGORIE == "Grundlage")
{
string Pruefgrundlage = i.IDOC.Z1ZRMDB.PRFBER.PRFERG.PRFTXT[c].Value;
int count_pg = pg.Count;
for (int cc = 0; cc < count_pg; cc++)
{
if (Pruefgrundlage.Contains(pg[cc]) == true)
{
Pruefgrundlage_VZ = pg[cc];
}
}
}
}
Auftraggeber = new string[7];
Aufstellungsort = new string[7];
Anlagen = new string[AnzahlAnlagen, 5];
Vorgang_rückgemeldet = new string[AnzahlAnlagen, 6];
Vorgang_zukünftig = new string[AnzahlAnlagen, 3];
}
Auftraggeber[0] = Name_AG;
Auftraggeber[1] = Stadt_AG;
Auftraggeber[2] = PLZ_AG;
Auftraggeber[3] = Straße_AG;
Auftraggeber[4] = Hausnummer_AG;
Auftraggeber[5] = Region_AG;
Auftraggeber[6] = PARNR_AG;
Aufstellungsort[0] = Name_AO;
Aufstellungsort[1] = Stadt_AO;
Aufstellungsort[2] = PLZ_AO;
Aufstellungsort[3] = Straße_AO;
Aufstellungsort[4] = Hausnummer_AO;
Aufstellungsort[5] = Region_AO;
Aufstellungsort[6] = Land_AO;
for (int j = 0; j < Anlagen.GetLength(0); j++)
{
Anlagen[j, 0] = Materialnummer;
Anlagen[j, 1] = EQnummer;
Anlagen[j, 2] = Anlagentyp;
Anlagen[j, 3] = InterneBezeichnung[j];
Anlagen[j, 4] = Hersteller[j];
Vorgang_rückgemeldet[j, 0] = Typ_VR;
Vorgang_rückgemeldet[j, 1] = Dienstleister;
Vorgang_rückgemeldet[j, 2] = Durchführungsdatum;
Vorgang_rückgemeldet[j, 3] = Maengel;
Vorgang_rückgemeldet[j, 4] = Bemerkungstexte;
Vorgang_rückgemeldet[j, 5] = Pruefgrundlage_VR;
Vorgang_zukünftig[j, 0] = Typ_VZ;
Vorgang_zukünftig[j, 1] = Fälligkeit;
Vorgang_zukünftig[j, 2] = Pruefgrundlage_VZ;
}
return (Auftraggeber, Aufstellungsort, Anlagen, Vorgang_rückgemeldet, Vorgang_zukünftig);
}
}
}
And here the class to simulate the xml structure:
using System;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
namespace EdocX
{//ZRM01 Root Environment
[Serializable()]
[XmlRoot(ElementName = "ZRM01")]
public partial class Document
{
[XmlElement()]
public ZRM01IDOC IDOC { get; set; }
}
//IDOC
[Serializable()]
public partial class ZRM01IDOC
{
[XmlElement()]
public ZRM01IDOCZ1ZRMDB Z1ZRMDB { get; set; }
}
//IDOC Elements
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDB
{
public string MABEZ { get; set; } // Materialnummer
public string OBJNR { get; set; } // Equipmentnummer
[XmlElement("Z1ZRMPA")]
public List<ZRM01IDOCZ1ZRMDBZ1ZRMPA> Z1ZRMPA = new List<ZRM01IDOCZ1ZRMDBZ1ZRMPA>(); //{ get; set; }
[XmlElement("Z1ZRMAU")]
public List<ZRM01IDOCZ1ZRMDBZ1ZRMAU> Z1ZRMAU = new List<ZRM01IDOCZ1ZRMDBZ1ZRMAU>();
[XmlElement()]
public ZRM01IDOCZ1ZRMDBPRFBER PRFBER { get; set; }
}
//Z1ZRMPA --> Mandant / Gebäude
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBZ1ZRMPA
{
[XmlAttribute()]
public string TITLE { get; set; } // "Auftraggeber" "Aufstellungsort"
[XmlElement()]
public string PARNR { get; set; } // Parnr. (Mandant)
[XmlElement()]
public string NAME1 { get; set; } // Name
[XmlElement()]
public string NAME2 { get; set; } // Name
[XmlElement()]
public string CITY1 { get; set; } // Stadt
[XmlElement()]
public string POST_CODE1 { get; set; } // PLZ
[XmlElement()]
public string STREET { get; set; } // Straße
[XmlElement()]
public string HOUSE_NUM1 { get; set; } // Hausnummer
[XmlElement()]
public string REGION { get; set; } // Region
[XmlElement()]
public string COUNTRY { get; set; } // Land
}
//Z1ZRMAU
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBZ1ZRMAU
{
[XmlElement()]
public string MNAME { get; set; } // "Nächste Wiederkehrende Prüfung"
[XmlElement()]
public string MWERT { get; set; } // Fälligkeit
}
//PRFBER Elemts
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBER
{
[XmlElement()]
public ZRM01IDOCZ1ZRMDBPRFBERPRFERG PRFERG { get; set; }
[XmlElement()]
public ZRM01IDOCZ1ZRMDBPRFBERDATEN DATEN { get; set; }
}
//DATEN
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERDATEN
{
[XmlElement()]
public string Pruefungszeitraum { get; set; } //Durchführungsdatum
}
//PRFERG Elements
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERPRFERG
{
[XmlElement()]
public ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGE ANLAGE { get; set; }
[XmlElement("PRFTXT")]
public List<ZRM01IDOCZ1ZRMDBPRFBERPRFERGPRFTXT> PRFTXT = new List<ZRM01IDOCZ1ZRMDBPRFBERPRFERGPRFTXT>();
}
//ANLAGE
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGE
{
[XmlElement("PRFTXT")]
public List<ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGEPRFTXT> PRFTXT = new List<ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGEPRFTXT>();
}
//PRFTXT
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERPRFERGANLAGEPRFTXT
{
[XmlAttribute()]
public string REF { get; set; } // Anzahl Anlagen
[XmlAttribute()]
public string HERSTELLER { get; set; } // Hersteller Anlage
[XmlAttribute()]
public string ENTRBEREICH { get; set; } // Interne Bezeichnung Anlage
}
//PRFTXT
[Serializable()]
public partial class ZRM01IDOCZ1ZRMDBPRFBERPRFERGPRFTXT
{
[XmlAttribute()]
public string KATEGORIE { get; set; } // A"Grundlage" < ... >
[XmlText()]
public string Value { get; set; }
[XmlAttribute()]
public string ROWTYPE { get; set; } // "Zwischenüberschrift" (für Mangel ja/nein) "Mangel" (für Bemerkungstext)
[XmlAttribute()]
public string PATTERN { get; set; } // "#KATEGORIE[../#KATEGORIE='Mangel' and ../#GEWICHT[not(contains(.,'Beseitigt'))]]" < Mängel > bzw < ... >
}
}
I'm very thankful for help!

C# DataGridView not populating from a separate form

I'm sorry if my title is bad, its 1:30am and I'm all out of coffee. I've tried a few solutions suggested on similar questions but I can't figure it out as my case is a little different.
I'm trying to use a separate form to select parameters for the method I use to format data which is passed to a DataGridView in the original form, however its not populating the DataGridView. I have set the new form to be a dialog, it receives the original form reference when its called, on the form there is a DateTimePicker and a button, when the button is clicked it calls a method that gets the datetime value, then it calls a method on the original form with the datetime parameters being passed to it and closes the dialog. The method on the original form runs with the parameters that where passed to get the data for the DataGridView and then calls the datasource method passing the bindinglist to it.
This method of filling the DataGridView using a dialog is my best interpretation of how its been explained in similar questions on this site but its not populating my DataGridView. Any help would be greatly appreciated.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SearchDialog search = new SearchDialog(this);
search.Show();
}
)button2 is a cancel button(
public partial class SearchDialog : Form
{
static DirectoryInfo DexFolder = new DirectoryInfo(Properties.Settings.Default.DexFolderPath);
static DirectoryInfo ExcelFile = new DirectoryInfo(Properties.Settings.Default.ExcelFilePath);
public SearchDialog(Main form)
{
InitializeComponent();
fromDateSelector.Checked = false;
toDateSelector.Checked = false;
MainForm = form;
}
public Main MainForm {get; set;}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
private void button1_Click(object sender, EventArgs e)
{
SearchParameters();
Close();
}
private void SearchParameters()
{
DateTime allTime = DateTime.Now.AddYears(-150);
DateTime current = DateTime.Now;
if (fromDateSelector.Checked == true)
{
allTime = fromDateSelector.Value;
}
if (toDateSelector.Checked == true)
{
current = toDateSelector.Value;
}
MainForm.GetFiles(DexFolder, current, allTime);
}
}
(back on Main form)
public void GetFiles(DirectoryInfo FilePath, DateTime from, DateTime to)
{
List<string> DexFileNames = new List<string>();
List<string> DexData = new List<string>();
IList<FileManagerView> fileManagerData = new BindingList<FileManagerView>();
string[] ExcelData = File.ReadAllLines(ExcelFile.ToString());
foreach (FileInfo fileInfo in FilePath.GetFiles("*.dex"))
{
DexFileNames.Add(fileInfo.Name);
}
foreach (string DexFileName in DexFileNames)
{
DateTime dexDate = File.GetCreationTime(FilePath + DexFileName);
string[] NameData = DexFileName.Split('_', '-', '.');
if (NameData.Length > 2)
{
dexDate = DateTime.ParseExact(NameData[1] + NameData[2], "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
}
string DexPHYSID = NameData[0];
string machineNumber = "";
string machineLocation = "";
string telemetryDevice = "";
string routeNumber = "";
string machinePHYSID = "";
string driverName = "";
foreach (string line in ExcelData)
{
string[] lineData = line.Split(',');
if (DexPHYSID == lineData[14].Trim('"'))
{
machinePHYSID = lineData[14].Trim('"');
machineNumber = lineData[0].Trim('"');
machineLocation = lineData[2].Trim('"');
string RouteNumberFull = lineData[17].Trim('"');
string[] DriverName = lineData[18].Trim('"').Split('(');
telemetryDevice = lineData[8].Trim('"');
string[] RouteNumberData = RouteNumberFull.Split(' ');
driverName = DriverName[0];
try
{
routeNumber = RouteNumberData[1] + " " + RouteNumberData[2];
}
catch
{
}
}
}
if (DexPHYSID == machinePHYSID)
{
FileManagerView fileManagerView = new FileManagerView();
if (dexDate.ToString("dd-MM-yy") == from.ToString("dd-MM-yy") && dexDate.ToString("dd-MM-yy") == to.ToString("dd-MM-yy"))
{
fileManagerView.machineNumber = machineNumber;
fileManagerView.machineLocation = machineLocation;
fileManagerView.telemetryDevice = telemetryDevice;
fileManagerView.physid = DexPHYSID;
fileManagerView.routeNumber = routeNumber;
fileManagerView.date = dexDate;
fileManagerView.driver = driverName;
fileManagerData.Add(fileManagerView);
}
}
}
FileManagerPopulate(fileManagerData);
}
public class FileManagerView
{
public string machineNumber { get; set; }
public string machineLocation { get; set; }
public string telemetryDevice { get; set; }
public string physid { get; set; }
public string routeNumber { get; set; }
public string driver { get; set; }
public DateTime date { get; set; }
}
public void FileManagerPopulate(IList<FileManagerView> data)
{
dataGridView1.DataSource = data;
}
So the problem was the use of == operands instead of > and < when the GetFiles() method was checking if the file date was within the selected range.
I'm going to leave this here as it may help someone else looking for answers.

match value in one list with another and write value to other list

I have one list that is written to this class:
public class keyfrs
{
public keyfrs() { }
public long regID { get; set; }
public long ID { get; set; }
public string county { get; set; }
public string state { get; set; }
}
List<keyfrs> k = {1,2,3,4}] regID
{A,B,C,D} ID
I have another list class like this:
public class states
{
public states() { }
public long regID { get; set; }
public string state { get; set; }
public string county { get; set; }
}
List<states> s = {1,2,3,4}regID
{MA,NY,CT}state
{Suffolk,NY,Hampden}county
Want to write the county and state to the keyfrs list that matches with the regID from the lists.
What my program does so far is parse in two files and write each one to the different class list it corresponds to. As you can see both classes have a regID column. What I need to do is match the two lists together on regID and write the county and state to the keyfrs list class to then output that list to a new file with these added column in it.
static void Main(string[] args)
{
PARSEkeYfrs();
parsestateFile();
matchValues();
outputFile();
}
private static void outputFile()
{
string filename = #"c:\keyswCounty.csv";
using(StreamWriter write = new StreamWriter(filename))
{
write.WriteLine("RegIF"+","+"ID"+","+"County"+","+"State");
foreach(keyfrs k in keysandID)
{
write.WriteLine(k.regID +"," +k.ID+","+k.county+","+k.state);
}
}
}
private static void matchValues()
{
foreach(keyfrs k in keysandID)
{
}
}
private static void parsestateFile()
{
int a = 0;
string filename = #"c:\ALLStates.txt";
using (StreamReader read = new StreamReader(filename))
{
read.ReadLine();
while (!read.EndOfStream)
{
a++;
try{
string line = read.ReadLine();
string[] splitline = line.Split(',');
if(splitline[1]!="")
{
states s = new states();
s.regID = Convert.ToInt64(splitline[0]);
s.county = Convert.ToString(splitline[1]);
s.state = Convert.ToString(splitline[2]);
stateFile.Add(s);
}
}
catch(Exception ex)
{
string.Format("error:{0}" + ex.Message.ToString());
}
}
}
}
private static void PARSEkeYfrs()
{ int a = 0;
string filename = #"c:\key_frs.csv";
using (StreamReader read = new StreamReader(filename))
{
read.ReadLine();
while (!read.EndOfStream)
{
try{
a++;
string line = read.ReadLine();
string[] splitline = line.Split(',');
if(splitline[1]!="")
{
keyfrs k = new keyfrs();
k.regID = Convert.ToInt64(splitline[0]);
k.ID = Convert.ToInt64(splitline[1]);
k.county = "";
k.state = "";
keysandID.Add(k);
}
}
catch(Exception ex)
{
string.Format("error:{0}"+ex.Message.ToString());
}
}
}
}
switched the state list to a dictionary and matched the values by the key value pair by using the TryGetValue method.

Categories

Resources