I am trying to search my text-file for a sentence by date and by name. Then I want this sentence to load it to some textboxes in my form. I am new in VS but I know some things about C.
I have came up with this code:
string pattern = dateTimePicker1Is.Text;
string pattern1 = _txtNameIs.Text;
IList<string> result = new List<string>();
using (var reader = new StreamReader(#"C:\Users\user\Desktop\Testet System\isto.txt"))
{
string currentLine;
while ((currentLine = reader.ReadLine()) != null)
{
if (currentLine.Contains(pattern))
{
if (currentLine.Contains(pattern1))
{
result.Add(currentLine);
string[] tempArray = currentLine.Split(',');
_txtNameIs.Text = tempArray[0];
_txtSurnameIs.Text = tempArray[1];
_txtApokxT.Text = tempArray[2];
_txtApoktT.Text = tempArray[3];
_txtEpanxT.Text = tempArray[4];
_txtEpandT.Text = tempArray[5];
_txtApokkT.Text = tempArray[6];
_txtEpankT.Text = tempArray[7];
_txtApoksT.Text = tempArray[8];
_txtEpansT.Text = tempArray[9];
_txtGenSun.Text = tempArray[10];
break;
}
else
{
MessageBox.Show("There are no records!");
}
}
}
}
When I press the search button it loads me all the data that I need, but if I have the same name and different date a message-box pops up and tells 'there are no records'.
I believe there is better way doing this:
string pattern = dateTimePicker1Is.Text;
string pattern1 = _txtNameIs.Text;
string pathToFile = #"C:\Users\user\Desktop\Testet System\isto.txt";
List<string> result = new List<string>();
foreach (var line in File.ReadAllLines(pathToFile))
{
if (line.Contains(pattern) && line.Contains(pattern1))
{
result.Add(line);
string[] tempArray = line.Split(',');
if(tempArray.Length >= 11)
{
_txtNameIs.Text = tempArray[0];
_txtSurnameIs.Text = tempArray[1];
_txtApokxT.Text = tempArray[2];
_txtApoktT.Text = tempArray[3];
_txtEpanxT.Text = tempArray[4];
_txtEpandT.Text = tempArray[5];
_txtApokkT.Text = tempArray[6];
_txtEpankT.Text = tempArray[7];
_txtApoksT.Text = tempArray[8];
_txtEpansT.Text = tempArray[9];
_txtGenSun.Text = tempArray[10];
break;
}
}
}
It is better to show message if the list count is 0.
I think your There are no records error should happen
AFTER the while statement
IF no matches were found
Right?
So put if there was a match found in a bool, and then after the while if !IsMatchFound then throw your error.
Related
I'm fairly new to C# and im writing a rental vehicle management system. I'm trying to retrieve all lines from a CSV file that is set up like this:
[Registration][Grade][Make][Model][Year][NumSeats][Transmission][Fuel][GPS][SunRoof][DailyRate][Colour]
[123ABC][Economy][Toyota][Camry][2005][5][Automatic][Petrol][No][No][30][White]
[234BCD][Economy][Ford][Focus][2012][5][Automatic][Petrol][Yes][No][45][Blue]
[987ZYX][Economy][Holden][Cruise][2016][5][Manual][Diesel][Yes][No][60][Red]
and then iterate it through a for loop before it's sent to another method.
In the following method beyond the one shown, it's being put into an ArrayList so that the values retrieved can be searched for by the user in the program.
I'm stuck on the for loop as it gives me an error on the vehicles1.Length; saying that vehicles1 is a use of an unassigned local variable. I don't know if initializing the array is my problem, because I've tried that and it gives me no errors but the program just breaks.
void setUpVehicles(out Fleet fleetVehicles)
{
const char DELIM = ',';
Vehicle veh = new Vehicle();
FileStream inFile = new FileStream(FILENAME3, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(inFile);
string recordIn;
string[] vehicles1;
recordIn = reader.ReadLine();
while (recordIn != null)
{
string year = veh.Year.ToString();
string seats = veh.NumSeats.ToString();
string gps = veh.GPS.ToString();
string sunRoof = veh.SunRoof.ToString();
string dailyRate = veh.DailyRate.ToString();
vehicles1 = recordIn.Split(DELIM);
veh.Registration = vehicles1[0];
veh.Grade = vehicles1[1];
veh.Make = vehicles1[2];
veh.Model = vehicles1[3];
year = vehicles1[4];
seats = vehicles1[5];
veh.Transmission = vehicles1[6];
veh.Fuel = vehicles1[7];
gps = vehicles1[8];
sunRoof = vehicles1[9];
dailyRate = vehicles1[10];
veh.Colour = vehicles1[11];
}
fleetVehicles = new Fleet();
for (int i = 0; i < vehicles1.Length; i++)
{
fleetVehicles.insertVehicle(vehicles1[i]);
}
}
IEnumerable<Vehicle> setUpVehicles(string fileName)
{
using(var reader = new StreamReader(fileName))
using(var parser = new Microsoft.VisualBasic.TextFieldParser(reader))
{
parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
parser.Delimiters = new string[] {","};
string[] row;
while(!parser.EndOfData)
{
row = parser.ReadFields();
var vehicle = new Vehicle {
Registration = row[0],
Grade = row[1],
Make = row[2],
Model = row[3],
Year = row[4],
NumSeats = row[5],
Transmission = row[6],
Fuel = row[7],
GPS = row[8],
SunRoo = row[9],
DailyRate = row[10],
Colour = row[11]
};
yield return vehicle;
}
}
}
Then you would call it to make a fleet like this:
var fleetVehicles = new Fleet();
foreach(var vehicle in setUpVehicles(FILENAME3))
{
feetVehicles.insertVehicles(vehicle);
}
Both the below cases are not working. I want to extract from a text file a certain part that I can choose by specifying the start of the line and end.
case looks like this:
using (StreamReader reader = new StreamReader("C:/Users/david/Desktop/20180820.log",Encoding.Default))
{
Console.WriteLine("From:");
string a = (Console.ReadLine());
Console.WriteLine(" To:");
string b = (Console.ReadLine());
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (line.StartsWith(a) && (line.EndsWith(b)))
{
Console.WriteLine(line);
}
}
}
case with regex
string line;
while ((line = reader.ReadLine()) != null)
{
string regex12 = a.ToString() + b.ToString();
Match m = Regex.Match(line,regex12);
string s = Regex.Match(line, regex12).Groups[0].Value;
Console.WriteLine(s);
if (m.Success)
{
string n = m.Groups[0].Value;
Console.WriteLine(n);
}
}
If anyone can solve my problem, I will be very thankful.
Update Based on Comments
From the comments, it looks like you are attempting to parse a specifically formatted file, and would better benefit with a non-generic solution. Also, it looks like the text is split across multiple lines, rather than single line as you had shared in comments.
[00:09:08.870] text...
[00:09:08.886] text...
[00:09:08.886] text...
[00:09:10.448] text...
[00:09:10.464] text...
[00:09:10.526] text...
[00:09:11.886] text...
[00:09:11.901] text...
[00:09:11.980] text...
[00:09:12.026] text...
In this case, you could use the following.
var reader = File.OpenText(filePAth);
var startLineDetected = false;
var startWord = "00:09:08.870";
var endWord = "00:09:12.026";
var strBuilder = new StringBuilder();
while(!reader.EndOfStream)
{
var newLine = reader.ReadLine();
if(newLine.Contains($"[{startWord}") && !startLineDetected)
{
startLineDetected = true;
}
if(newLine.Contains($"[{endWord}") && startLineDetected)
{
strBuilder.AppendLine(newLine);
break;
}
if(startLineDetected)
{
strBuilder.AppendLine(newLine);
}
}
var resultData = strBuilder.ToString();
Original Answer based on OP
You could do the following.
var reader = File.OpenText(filePAth);
var startLineDetected = false;
var startWord = // startWord;
var endWord = // endWord;
var strBuilder = new StringBuilder();
while(!reader.EndOfStream)
{
var newLine = reader.ReadLine();
if(newLine.Contains(startWord) && !startLineDetected)
{
startLineDetected = true;
newLine = newLine.Substring(newLine.IndexOf(startWord));
}
if(newLine.Contains(endWord) && startLineDetected)
{
newLine = newLine.Substring(0,newLine.IndexOf(endWord) + endWord.Length);
strBuilder.Append(newLine);
break;
}
if(startLineDetected)
{
strBuilder.Append(newLine);
}
}
var resultData = strBuilder.ToString();
i have a problem that i change selected index in listview it works fine when i change first time but when i change second time it says "InvalidArgument=Value of '0' is not valid for 'index'."
the code is this ;
listBox1.Items.Clear();
string a = "";
a = "";
a = listView1.SelectedItems[0].SubItems[0].Text;
StreamReader oku = new StreamReader(strPath+"\\"+"Versiyonlar"+"\\"+a);
string OkunanVeri = oku.ReadToEnd();
string[] dizi = OkunanVeri.Split(new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);
foreach (var item in dizi)
{
listBox1.Items.Add(item);
}
oku.Close();
strpath is way to desktop
try
{
listBox1.Items.Clear();
string a = "";
a = "";
a = listView1.SelectedItems[0].SubItems[0].Text;
StreamReader oku = new StreamReader(strPath+"\\"+"Versiyonlar"+"\\"+a);
string OkunanVeri = oku.ReadToEnd();
string[] dizi = OkunanVeri.Split(new string[]{"\r\n"},StringSplitOptions.RemoveEmptyEntries);
foreach (var item in dizi)
{
listBox1.Items.Add(item);
}
oku.Close();
}
catch
{
}
i just fixed it like this
I have created a C# program to read a pipe ("|") delimited file and create purchase invoices and lines. Essentially, I have it loop through each line, if the "Report ID" has not been used, it creates a header, then the line, if the header has been created, it skips the header creation and is supposed to add the subsequent line. However, when I reach my object assignment for the line, it errors with:
"ArgumentException was unhandled"
"Must specify valid information for parsing the string."
The PIheader function works fine, so I have not included here. Please advise if more information/code is needed.
//Parse selected SAE File
SAEline[] sae = ParseSAE.Parse(file);
//Begin Analyzing Data
int saesize = sae.Length;
int i = 0;
List<string> cashIDs = new List<string>();
string paymentterms = "";
string invno = "";
string company = "";
string[] getcompany = new string[2];
string reportid = sae[i].ReportID;
int lineno = 0;
while(i < 10) //limit the loop for testing
//while (i < saesize)
{
if (sae[i].ReportEntryPaymentCodeCode != "CBCP")
{
if (!cashIDs.Contains(reportid))
{
cashIDs.Add(reportid);
getcompany = WebServices.GetCompany(sae[i].EmployeeID.ToUpper());
paymentterms = sae[i].ReportEntryPaymentCodeCode;
invno = WebServices.PIheader(getcompany[0], getcompany[1], 0, sae[i]);
lineno = 0;
}
lineno = lineno + 10000;
company = getcompany[0];
lineno = WebServices.PIlines(invno, lineno, company, sae[i]);
}
i++;
}
The WebService.cs contains:
//Web Service Client
PurchLines.PurchLines_PortClient piClient =
new PurchLines_PortClient((System.ServiceModel.Channels.Binding)basicHttpBindingNTLM,
new EndpointAddress("URL" + company + "/Page/PurchLines"));
//Conditional variables
string joblinetype = "";
string qty = "";
if (sae.ReportEntryCustom1 == "Billable")
{
joblinetype = "3";
}
if (sae.BusinessDistance == "")
{
if (sae.ReportCustom2 == "")
{
qty = "1";
}
else
{
qty = sae.ReportCustom2;
}
}
else
{
qty = sae.BusinessDistance;
}
string unitcost = (Convert.ToDecimal(sae.ReportEntryApprovedAmount)/Convert.ToDecimal(qty)).ToString();
//Line Creation
PurchLines.PurchLines line = new PurchLines.PurchLines()
{
No = sae.JournalAccountCode,
Line_No = Convert.ToInt16(lineno),
Line_NoSpecified = true,
Job_Line_TypeSpecified = true,
Job_Line_Type = (PurchLines.Job_Line_Type) (Enum.Parse(typeof (PurchLines.Job_Line_Type), joblinetype)),
QuantitySpecified = true,
Quantity = Convert.ToDecimal(qty),
TypeSpecified = true,
Type = (PurchLines.Type) (Enum.Parse(typeof (PurchLines.Type), "1")),
Direct_Unit_CostSpecified = true,
Direct_Unit_Cost = Convert.ToDecimal(unitcost),
Job_Unit_PriceSpecified = true,
Job_Unit_Price = Convert.ToDecimal(unitcost),
Job_No = sae.ReportEntryCustom5,
Job_Task_No = sae.ReportEntryCustom6,
Document_TypeSpecified = true,
Document_Type = (PurchLines.Document_Type)(Enum.Parse(typeof(PurchLines.Document_Type),"2")),
Document_No = invno
};
piClient.Create(ref line);
PurchLines.Create_Result result = new PurchLines.Create_Result(line);
int lin = result.PurchLines.Line_No;
return lin;
}
I realized that I didn't assign a value to joblinetype in the event that it is not "Billable", so the webservice was unable to Parse the blank string
Job_Line_Type = (PurchLines.Job_Line_Type) (Enum.Parse(typeof (PurchLines.Job_Line_Type), joblinetype)),
I'm importing records from a text file into my DB. I have it setup to check the record that I to ensure there is not already a duplicate in the database. If there is already an entry in the database it skips that record.
Now the issue I need to address is when there is not a record in the text file but there is a record in the database. I need to remove the record from the database that does not match any records in the file.
public static void ParseComplaint(string location)
{
Console.WriteLine("Parsing.....");
List<AutoMakeNoEntity> am = DBCacheHelper.GetAllMakes().ToList<AutoMakeNoEntity>();
using (var reader = new StreamReader(location))
{
foreach (string line in File.ReadLines(location))
{
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
var tokens = line.Trim().Split(new char[] { '\t' });
if (am.Any(c => c.MakeName == tokens[3]))
{
using (RecallsContext context = new RecallsContext())
{
string tmp = tokens[0];
if (!context.complaints.Any(c => c.CMPLID == tmp))
{
var recalls = new Complaints();
recalls.CMPLID = tokens[0];
recalls.ODINO = tokens[1];
recalls.MFR_NAME = tokens[2];
recalls.MAKETXT = tokens[3];
recalls.MODELTXT = tokens[4];
recalls.YEARTXT = tokens[5];
recalls.CRASH = tokens[6];
recalls.FAILDATE = tokens[7];
recalls.FIRE = tokens[8];
recalls.INJURED = tokens[9];
recalls.DEATHS = tokens[10];
recalls.COMPDESC = tokens[11];
recalls.CITY = tokens[12];
recalls.STATE = tokens[13];
recalls.VIN = tokens[14];
recalls.DATEA = tokens[15];
recalls.LDATE = tokens[16];
recalls.MILES = tokens[17];
recalls.OCCURENCES = tokens[18];
recalls.CDESCR = tokens[19];
recalls.CMPL_TYPE = tokens[20];
recalls.POLICE_RPT_YN = tokens[21];
recalls.PURCH_DT = tokens[22];
recalls.ORIG_OWNER_YN = tokens[23];
recalls.ANTI_BRAKES_YN = tokens[24];
recalls.CRUISE_CONT_YN = tokens[25];
recalls.NUM_CYLS = tokens[26];
recalls.DRIVE_TRAIN = tokens[27];
recalls.FUEL_SYS = tokens[28];
recalls.FUEL_TYPE = tokens[29];
recalls.TRANS_TYPE = tokens[30];
recalls.VEH_SPEED = tokens[31];
recalls.DOT = tokens[32];
recalls.TIRE_SIZE = tokens[33];
recalls.LOC_OF_TIRE = tokens[34];
recalls.TIRE_FAIL_TYPE = tokens[35];
recalls.ORIG_EQUIP_YN = tokens[36];
recalls.MANUF_DT = tokens[37];
recalls.SEAT_TYPE = tokens[38];
recalls.RESTRAINT_TYPE = tokens[39];
recalls.DEALER_NAME = tokens[40];
recalls.DEALER_TEL = tokens[41];
recalls.DEALER_CITY = tokens[42];
recalls.DEALER_STATE = tokens[43];
recalls.DEALER_ZIP = tokens[44];
recalls.PROD_TYPE = tokens[45];
if (tokens.Length == 47)
{
recalls.REPAIRED_YN = tokens[46];
}
context.complaints.Add(recalls);
context.SaveChanges();
recalls.Dispose();
}
}
}
}
}
}
I need to remove the record from the database that does not match any records in the file.
If you want the database to match the contents of the text file, why don't you simply empty it first?